views_plugin_query_default.inc 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  1. <?php
  2. /**
  3. * @file
  4. * Definition of views_plugin_query_default.
  5. */
  6. /**
  7. * Object used to create a SELECT query.
  8. *
  9. * @ingroup views_query_plugins
  10. */
  11. class views_plugin_query_default extends views_plugin_query {
  12. /**
  13. * A list of tables in the order they should be added, keyed by alias.
  14. */
  15. public $table_queue = array();
  16. /**
  17. * Holds an array of tables and counts added so that we can create aliases.
  18. */
  19. public $tables = array();
  20. /**
  21. * Holds an array of relationships, which are aliases of the primary
  22. * table that represent different ways to join the same table in.
  23. */
  24. public $relationships = array();
  25. /**
  26. * An array of sections of the WHERE query. Each section is in itself
  27. * an array of pieces and a flag as to whether or not it should be AND
  28. * or OR.
  29. */
  30. public $where = array();
  31. /**
  32. * An array of sections of the HAVING query. Each section is in itself
  33. * an array of pieces and a flag as to whether or not it should be AND
  34. * or OR.
  35. */
  36. public $having = array();
  37. /**
  38. * The default operator to use when connecting the WHERE groups. May be
  39. * AND or OR.
  40. */
  41. public $group_operator = 'AND';
  42. /**
  43. * A simple array of order by clauses.
  44. */
  45. public $orderby = array();
  46. /**
  47. * A simple array of group by clauses.
  48. */
  49. public $groupby = array();
  50. /**
  51. * An array of fields.
  52. */
  53. public $fields = array();
  54. /**
  55. * The table header to use for tablesort. This matters because tablesort
  56. * needs to modify the query and needs the header.
  57. */
  58. public $header = array();
  59. /**
  60. * A flag as to whether or not to make the primary field distinct.
  61. */
  62. public $distinct = FALSE;
  63. /**
  64. *
  65. */
  66. public $has_aggregate = FALSE;
  67. /**
  68. * Should this query be optimized for counts, for example no sorts.
  69. */
  70. public $get_count_optimized = NULL;
  71. /**
  72. * The current used pager plugin.
  73. *
  74. * @var views_plugin_pager
  75. */
  76. public $pager = NULL;
  77. /**
  78. * An array mapping table aliases and field names to field aliases.
  79. */
  80. public $field_aliases = array();
  81. /**
  82. * Query tags which will be passed over to the dbtng query object.
  83. */
  84. public $tags = array();
  85. /**
  86. * Is the view marked as not distinct.
  87. *
  88. * @var bool
  89. */
  90. public $no_distinct;
  91. /**
  92. * Defines the distinct type.
  93. * - FALSE if it's distinct by base field.
  94. * - TRUE if it just adds the sql distinct keyword.
  95. *
  96. * @var bool
  97. */
  98. public $pure_distinct = FALSE;
  99. /**
  100. * {@inheritdoc}
  101. */
  102. public function init($base_table = 'node', $base_field = 'nid', $options) {
  103. parent::init($base_table, $base_field, $options);
  104. $this->base_table = $base_table;
  105. // Predefine these above, for clarity.
  106. $this->base_field = $base_field;
  107. $this->relationships[$base_table] = array(
  108. 'link' => NULL,
  109. 'table' => $base_table,
  110. 'alias' => $base_table,
  111. 'base' => $base_table,
  112. );
  113. // Unit the table queue with our primary table.
  114. $this->table_queue[$base_table] = array(
  115. 'alias' => $base_table,
  116. 'table' => $base_table,
  117. 'relationship' => $base_table,
  118. 'join' => NULL,
  119. );
  120. // Init the tables with our primary table.
  121. $this->tables[$base_table][$base_table] = array(
  122. 'count' => 1,
  123. 'alias' => $base_table,
  124. );
  125. // We no longer want the base field to appear automatically.
  126. // if ($base_field) {
  127. // $this->fields[$base_field] = array(
  128. // 'table' => $base_table,
  129. // 'field' => $base_field,
  130. // 'alias' => $base_field,
  131. // );
  132. // }
  133. $this->count_field = array(
  134. 'table' => $base_table,
  135. 'field' => $base_field,
  136. 'alias' => $base_field,
  137. 'count' => TRUE,
  138. );
  139. }
  140. /**
  141. * Utility methods to set flags and data.
  142. */
  143. /**
  144. * Set the view to be distinct.
  145. *
  146. * There are either distinct per base field or distinct in the pure sql way,
  147. * based on $pure_distinct.
  148. *
  149. * @param bool $value
  150. * Should the view by distincted.
  151. * @param bool $pure_distinct
  152. * Should only the sql keyword be added.
  153. */
  154. public function set_distinct($value = TRUE, $pure_distinct = FALSE) {
  155. if (!(isset($this->no_distinct) && $value)) {
  156. $this->distinct = $value;
  157. $this->pure_distinct = $pure_distinct;
  158. }
  159. }
  160. /**
  161. * Set what field the query will count() on for paging.
  162. */
  163. public function set_count_field($table, $field, $alias = NULL) {
  164. if (empty($alias)) {
  165. $alias = $table . '_' . $field;
  166. }
  167. $this->count_field = array(
  168. 'table' => $table,
  169. 'field' => $field,
  170. 'alias' => $alias,
  171. 'count' => TRUE,
  172. );
  173. }
  174. /**
  175. * Set the table header.
  176. *
  177. * Used for click-sorting because it's needed info to modify the ORDER BY
  178. * clause.
  179. */
  180. public function set_header($header) {
  181. $this->header = $header;
  182. }
  183. /**
  184. * {@inheritdoc}
  185. */
  186. public function option_definition() {
  187. $options = parent::option_definition();
  188. $options['disable_sql_rewrite'] = array(
  189. 'default' => FALSE,
  190. 'translatable' => FALSE,
  191. 'bool' => TRUE,
  192. );
  193. $options['distinct'] = array(
  194. 'default' => FALSE,
  195. 'bool' => TRUE,
  196. );
  197. $options['pure_distinct'] = array(
  198. 'default' => FALSE,
  199. 'bool' => TRUE,
  200. );
  201. $options['slave'] = array(
  202. 'default' => FALSE,
  203. 'bool' => TRUE,
  204. );
  205. $options['query_comment'] = array(
  206. 'default' => '',
  207. );
  208. $options['query_tags'] = array(
  209. 'default' => array(),
  210. );
  211. return $options;
  212. }
  213. /**
  214. * Add settings for the ui.
  215. */
  216. public function options_form(&$form, &$form_state) {
  217. parent::options_form($form, $form_state);
  218. // Establish which query tag will be affected by disable_sql_rewrite.
  219. // This 'access query tag' is defined by hook_views_data() for the base table.
  220. // e.g. node_views_data()
  221. if (!empty($form_state['view']->base_table)) {
  222. $base_table = $form_state['view']->base_table;
  223. $base_table_data = views_fetch_data($base_table);
  224. if (!empty($base_table_data['table']['base']['access query tag'])) {
  225. $access_tag = $base_table_data['table']['base']['access query tag'];
  226. $disable_rewrite = !empty($this->options['disable_sql_rewrite']);
  227. $form['disable_sql_rewrite'] = array(
  228. '#title' => t('Disable access checks'),
  229. '#description' => t('Do not apply %access_tag checks to this query. Selecting this option omits that tag from the alterable query.', array('%access_tag' => $access_tag)),
  230. '#type' => 'checkbox',
  231. '#default_value' => $disable_rewrite,
  232. '#suffix' => '<div class="messages warning sql-rewrite-warning' . ($disable_rewrite ? '' : ' js-hide') . '">'
  233. . t('WARNING: Disabling access checks means that %access_tag security is disabled. This may allow users to see data they should not be able to see if your view is misconfigured. Please use this option only if you understand and accept this security risk.', array('%access_tag' => $access_tag))
  234. . '</div>',
  235. );
  236. }
  237. }
  238. $form['distinct'] = array(
  239. '#type' => 'checkbox',
  240. '#title' => t('Distinct'),
  241. '#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.'),
  242. '#default_value' => !empty($this->options['distinct']),
  243. );
  244. $form['pure_distinct'] = array(
  245. '#type' => 'checkbox',
  246. '#title' => t('Pure Distinct'),
  247. '#description' => t('This will prevent views from adding the base column to the distinct field. If this is not selected and the base column is a primary key, then a non-pure distinct will not function properly because the primary key is always unique.'),
  248. '#default_value' => !empty($this->options['pure_distinct']),
  249. '#dependency' => array('edit-query-options-distinct' => '1'),
  250. );
  251. $form['slave'] = array(
  252. '#type' => 'checkbox',
  253. '#title' => t('Use Slave Server'),
  254. '#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.'),
  255. '#default_value' => !empty($this->options['slave']),
  256. );
  257. $form['query_comment'] = array(
  258. '#type' => 'textfield',
  259. '#title' => t('Query Comment'),
  260. '#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.'),
  261. '#default_value' => $this->options['query_comment'],
  262. );
  263. $form['query_tags'] = array(
  264. '#type' => 'textfield',
  265. '#title' => t('Query Tags'),
  266. '#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.'),
  267. '#default_value' => implode(', ', $this->options['query_tags']),
  268. '#element_validate' => array('views_element_validate_tags'),
  269. );
  270. }
  271. /**
  272. * Special submit handling.
  273. */
  274. public function options_submit(&$form, &$form_state) {
  275. $element = array('#parents' => array('query', 'options', 'query_tags'));
  276. $value = explode(',', drupal_array_get_nested_value($form_state['values'], $element['#parents']));
  277. $value = array_filter(array_map('trim', $value));
  278. form_set_value($element, $value, $form_state);
  279. }
  280. /**
  281. * Table/join adding.
  282. */
  283. /**
  284. * A relationship is an alternative endpoint to a series of table joins.
  285. *
  286. * Relationships must be aliases of the primary table and they must join
  287. * either to the primary table or to a pre-existing relationship.
  288. *
  289. * An example of a relationship would be a nodereference table. If you have a
  290. * nodereference named 'book_parent' which links to a parent node, you could
  291. * set up a relationship 'node_book_parent' to 'node'. Then, anything that
  292. * links to 'node' can link to 'node_book_parent' instead, thus allowing all
  293. * properties of both nodes to be available in the query.
  294. *
  295. * @param string $alias
  296. * What this relationship will be called, and is also the alias for the
  297. * table.
  298. * @param views_join $join
  299. * A views_join object (or derived object) to join the alias in.
  300. * @param string $base
  301. * The name of the 'base' table this relationship represents; this tells the
  302. * join search which path to attempt to use when finding the path to this
  303. * relationship.
  304. * @param string $link_point
  305. * If this relationship links to something other than the primary table,
  306. * specify that table here. For example, a 'track' node might have a
  307. * relationship to an 'album' node, which might have a relationship to an
  308. * 'artist' node.
  309. */
  310. public function add_relationship($alias, $join, $base, $link_point = NULL) {
  311. if (empty($link_point)) {
  312. $link_point = $this->base_table;
  313. }
  314. elseif (!array_key_exists($link_point, $this->relationships)) {
  315. return FALSE;
  316. }
  317. // Make sure $alias isn't already used; if it, start adding stuff.
  318. $alias_base = $alias;
  319. $count = 1;
  320. while (!empty($this->relationships[$alias])) {
  321. $alias = $alias_base . '_' . $count++;
  322. }
  323. // Make sure this join is adjusted for our relationship.
  324. if ($link_point && isset($this->relationships[$link_point])) {
  325. $join = $this->adjust_join($join, $link_point);
  326. }
  327. // Add the table directly to the queue to avoid accidentally marking it.
  328. $this->table_queue[$alias] = array(
  329. 'table' => $join->table,
  330. 'num' => 1,
  331. 'alias' => $alias,
  332. 'join' => $join,
  333. 'relationship' => $link_point,
  334. );
  335. $this->relationships[$alias] = array(
  336. 'link' => $link_point,
  337. 'table' => $join->table,
  338. 'base' => $base,
  339. );
  340. $this->tables[$this->base_table][$alias] = array(
  341. 'count' => 1,
  342. 'alias' => $alias,
  343. );
  344. return $alias;
  345. }
  346. /**
  347. * Add a table to the query, ensuring the path exists.
  348. *
  349. * This function will test to ensure that the path back to the primary table
  350. * is valid and exists; if you do not wish for this testing to occur, use
  351. * $query->queue_table() instead.
  352. *
  353. * @param string $table
  354. * The name of the table to add. It needs to exist in the global table
  355. * array.
  356. * @param string $relationship
  357. * An alias of a table; if this is set, the path back to this table will be
  358. * tested prior to adding the table, making sure that all intermediary
  359. * tables exist and are properly aliased. If set to NULL the path to the
  360. * primary table will be ensured. If the path cannot be made, the table
  361. * will NOT be added.
  362. * @param views_join $join
  363. * In some join configurations this table may actually join back through a
  364. * different method; this is most likely to be used when tracing a
  365. * hierarchy path. (node->parent->parent2->parent3). This parameter will
  366. * specify how this table joins if it is not the default.
  367. * @param string $alias
  368. * A specific alias to use, rather than the default alias.
  369. *
  370. * @return string
  371. * The alias of the table; this alias can be used to access information
  372. * about the table and should always be used to refer to the table when
  373. * adding parts to the query. Or FALSE if the table was not able to be
  374. * added.
  375. */
  376. public function add_table($table, $relationship = NULL, $join = NULL, $alias = NULL) {
  377. if (!$this->ensure_path($table, $relationship, $join)) {
  378. return FALSE;
  379. }
  380. if ($join && $relationship) {
  381. $join = $this->adjust_join($join, $relationship);
  382. }
  383. return $this->queue_table($table, $relationship, $join, $alias);
  384. }
  385. /**
  386. * Add a table to the query without ensuring the path.
  387. *
  388. * This is a pretty internal function to Views and add_table() or
  389. * ensure_table() should be used instead of this one, unless you are
  390. * absolutely sure this is what you want.
  391. *
  392. * @param string $table
  393. * The name of the table to add. It needs to exist in the global table
  394. * array.
  395. * @param string $relationship
  396. * The primary table alias this table is related to. If not set, the
  397. * primary table will be used.
  398. * @param views_join $join
  399. * In some join configurations this table may actually join back through a
  400. * different method; this is most likely to be used when tracing a
  401. * hierarchy path. (node->parent->parent2->parent3). This parameter will
  402. * specify how this table joins if it is not the default.
  403. * @param string $alias
  404. * A specific alias to use, rather than the default alias.
  405. *
  406. * @return string
  407. * The alias of the table; this alias can be used to access information
  408. * about the table and should always be used to refer to the table when
  409. * adding parts to the query. Or FALSE if the table was not able to be
  410. * added.
  411. */
  412. public function queue_table($table, $relationship = NULL, $join = NULL, $alias = NULL) {
  413. // If the alias is set, make sure it doesn't already exist.
  414. if (isset($this->table_queue[$alias])) {
  415. return $alias;
  416. }
  417. if (empty($relationship)) {
  418. $relationship = $this->base_table;
  419. }
  420. if (!array_key_exists($relationship, $this->relationships)) {
  421. return FALSE;
  422. }
  423. if (!$alias && $join && $relationship && !empty($join->adjusted) && $table != $join->table) {
  424. if ($relationship == $this->base_table) {
  425. $alias = $table;
  426. }
  427. else {
  428. $alias = $relationship . '_' . $table;
  429. }
  430. }
  431. // Check this again to make sure we don't blow up existing aliases for
  432. // already adjusted joins.
  433. if (isset($this->table_queue[$alias])) {
  434. return $alias;
  435. }
  436. $alias = $this->mark_table($table, $relationship, $alias);
  437. // If no alias is specified, give it the default.
  438. if (!isset($alias)) {
  439. $alias = $this->tables[$relationship][$table]['alias'] . $this->tables[$relationship][$table]['count'];
  440. }
  441. // If this is a relationship based table, add a marker with the
  442. // relationship as a primary table for the alias.
  443. if ($table != $alias) {
  444. $this->mark_table($alias, $this->base_table, $alias);
  445. }
  446. // If no join is specified, pull it from the table data.
  447. if (!isset($join)) {
  448. $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
  449. if (empty($join)) {
  450. return FALSE;
  451. }
  452. $join = $this->adjust_join($join, $relationship);
  453. }
  454. $this->table_queue[$alias] = array(
  455. 'table' => $table,
  456. 'num' => $this->tables[$relationship][$table]['count'],
  457. 'alias' => $alias,
  458. 'join' => $join,
  459. 'relationship' => $relationship,
  460. );
  461. return $alias;
  462. }
  463. /**
  464. *
  465. */
  466. public function mark_table($table, $relationship, $alias) {
  467. // Mark that this table has been added.
  468. if (empty($this->tables[$relationship][$table])) {
  469. if (!isset($alias)) {
  470. $alias = '';
  471. if ($relationship != $this->base_table) {
  472. // Double underscore will help prevent accidental name space
  473. // collisions.
  474. $alias = $relationship . '__';
  475. }
  476. $alias .= $table;
  477. }
  478. $this->tables[$relationship][$table] = array(
  479. 'count' => 1,
  480. 'alias' => $alias,
  481. );
  482. }
  483. else {
  484. $this->tables[$relationship][$table]['count']++;
  485. }
  486. return $alias;
  487. }
  488. /**
  489. * Ensure a table exists in the queue; if it already exists it won't do
  490. * anything, but if it doesn't it will add the table queue. It will ensure a
  491. * path leads back to the relationship table.
  492. *
  493. * @param string $table
  494. * The unaliased name of the table to ensure.
  495. * @param string $relationship
  496. * The relationship to ensure the table links to. Each relationship will
  497. * get a unique instance of the table being added. If not specified, will
  498. * be the primary table.
  499. * @param views_join $join
  500. * A views_join object (or derived object) to join the alias in.
  501. *
  502. * @return string
  503. * The alias used to refer to this specific table, or NULL if the table
  504. * cannot be ensured.
  505. */
  506. public function ensure_table($table, $relationship = NULL, $join = NULL) {
  507. // Ensure a relationship.
  508. if (empty($relationship)) {
  509. $relationship = $this->base_table;
  510. }
  511. // If the relationship is the primary table, this actually be a relationship
  512. // link back from an alias. We store all aliases along with the primary
  513. // table to detect this state, because eventually it'll hit a table we
  514. // already have and that's when we want to stop.
  515. if ($relationship == $this->base_table && !empty($this->tables[$relationship][$table])) {
  516. return $this->tables[$relationship][$table]['alias'];
  517. }
  518. if (!array_key_exists($relationship, $this->relationships)) {
  519. return FALSE;
  520. }
  521. if ($table == $this->relationships[$relationship]['base']) {
  522. return $relationship;
  523. }
  524. // If we do not have join info, fetch it.
  525. if (!isset($join)) {
  526. $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
  527. }
  528. // If it can't be fetched, this won't work.
  529. if (empty($join)) {
  530. return;
  531. }
  532. // Adjust this join for the relationship, which will ensure that the 'base'
  533. // table it links to is correct. Tables adjoined to a relationship
  534. // join to a link point, not the base table.
  535. $join = $this->adjust_join($join, $relationship);
  536. if ($this->ensure_path($table, $relationship, $join)) {
  537. // Attempt to eliminate redundant joins. If this table's relationship
  538. // and join exactly matches an existing table's relationship and join, we
  539. // do not have to join to it again; just return the existing table's
  540. // alias.
  541. // @see http://groups.drupal.org/node/11288
  542. //
  543. // This can be done safely here but not lower down in queue_table(),
  544. // because queue_table() is also used by add_table() which requires the
  545. // ability to intentionally add the same table with the same join
  546. // multiple times. For example, a view that filters on 3 taxonomy terms
  547. // using AND needs to join taxonomy_term_data 3 times with the same join.
  548. // scan through the table queue to see if a matching join and
  549. // relationship exists. If so, use it instead of this join.
  550. // @todo Scanning through $this->table_queue results in an O(N^2)
  551. // algorithm, and this code runs every time the view is instantiated
  552. // (Views 2 does not currently cache queries). There are a couple
  553. // possible "improvements" but we should do some performance testing
  554. // before picking one.
  555. foreach ($this->table_queue as $queued_table) {
  556. // In PHP 4 and 5, the == operation returns TRUE for two objects if
  557. // they are instances of the same class and have the same attributes
  558. // and values.
  559. if ($queued_table['relationship'] == $relationship && $queued_table['join'] == $join) {
  560. return $queued_table['alias'];
  561. }
  562. }
  563. return $this->queue_table($table, $relationship, $join);
  564. }
  565. }
  566. /**
  567. * Make sure that the specified table can be properly linked to the primary
  568. * table in the JOINs. This function uses recursion. If the tables needed
  569. * to complete the path back to the primary table are not in the query they
  570. * will be added, but additional copies will NOT be added if the table is
  571. * already there.
  572. */
  573. public function ensure_path($table, $relationship = NULL, $join = NULL, $traced = array(), $add = array()) {
  574. if (!isset($relationship)) {
  575. $relationship = $this->base_table;
  576. }
  577. if (!array_key_exists($relationship, $this->relationships)) {
  578. return FALSE;
  579. }
  580. // If we do not have join info, fetch it.
  581. if (!isset($join)) {
  582. $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
  583. }
  584. // If it can't be fetched, this won't work.
  585. if (empty($join)) {
  586. return FALSE;
  587. }
  588. // Does a table along this path exist?
  589. if (isset($this->tables[$relationship][$table]) ||
  590. ($join && $join->left_table == $relationship) ||
  591. ($join && $join->left_table == $this->relationships[$relationship]['table'])) {
  592. // Make sure that we're linking to the correct table for our relationship.
  593. foreach (array_reverse($add) as $table => $path_join) {
  594. $this->queue_table($table, $relationship, $this->adjust_join($path_join, $relationship));
  595. }
  596. return TRUE;
  597. }
  598. // Have we been this way?
  599. if (isset($traced[$join->left_table])) {
  600. // We looped. Broked.
  601. return FALSE;
  602. }
  603. // Do we have to add this table?
  604. $left_join = $this->get_join_data($join->left_table, $this->relationships[$relationship]['base']);
  605. if (!isset($this->tables[$relationship][$join->left_table])) {
  606. $add[$join->left_table] = $left_join;
  607. }
  608. // Keep looking.
  609. $traced[$join->left_table] = TRUE;
  610. return $this->ensure_path($join->left_table, $relationship, $left_join, $traced, $add);
  611. }
  612. /**
  613. * Fix a join to adhere to the proper relationship.
  614. *
  615. * The left table can vary based upon what relationship items are joined in
  616. * on.
  617. */
  618. public function adjust_join($join, $relationship) {
  619. if (!empty($join->adjusted)) {
  620. return $join;
  621. }
  622. if (empty($relationship) || empty($this->relationships[$relationship])) {
  623. return $join;
  624. }
  625. // Adjusts the left table for our relationship.
  626. if ($relationship != $this->base_table) {
  627. // If we're linking to the primary table, the relationship to use will
  628. // be the prior relationship. Unless it's a direct link. Safety! Don't
  629. // modify an original here.
  630. $join = clone $join;
  631. // Do we need to try to ensure a path?
  632. if ($join->left_table != $this->relationships[$relationship]['table'] &&
  633. $join->left_table != $this->relationships[$relationship]['base'] &&
  634. !isset($this->tables[$relationship][$join->left_table]['alias'])) {
  635. $this->ensure_table($join->left_table, $relationship);
  636. }
  637. // First, if this is our link point/anchor table, just use the
  638. // relationship.
  639. if ($join->left_table == $this->relationships[$relationship]['table']) {
  640. $join->left_table = $relationship;
  641. }
  642. // then, try the base alias.
  643. elseif (isset($this->tables[$relationship][$join->left_table]['alias'])) {
  644. $join->left_table = $this->tables[$relationship][$join->left_table]['alias'];
  645. }
  646. // But if we're already looking at an alias, use that instead.
  647. elseif (isset($this->table_queue[$relationship]['alias'])) {
  648. $join->left_table = $this->table_queue[$relationship]['alias'];
  649. }
  650. }
  651. $join->adjusted = TRUE;
  652. return $join;
  653. }
  654. /**
  655. * Retrieve join data from the larger join data cache.
  656. *
  657. * @param string $table
  658. * The table to get the join information for.
  659. * @param string $base_table
  660. * The path we're following to get this join.
  661. *
  662. * @return views_join
  663. * A views_join object or child object, if one exists.
  664. */
  665. public function get_join_data($table, $base_table) {
  666. // Check to see if we're linking to a known alias. If so, get the real
  667. // table's data instead.
  668. if (!empty($this->table_queue[$table])) {
  669. $table = $this->table_queue[$table]['table'];
  670. }
  671. return views_get_table_join($table, $base_table);
  672. }
  673. /**
  674. * Get the information associated with a table.
  675. *
  676. * If you need the alias of a table with a particular relationship, use
  677. * ensure_table().
  678. */
  679. public function get_table_info($table) {
  680. if (!empty($this->table_queue[$table])) {
  681. return $this->table_queue[$table];
  682. }
  683. // In rare cases we might *only* have aliased versions of the table.
  684. if (!empty($this->tables[$this->base_table][$table])) {
  685. $alias = $this->tables[$this->base_table][$table]['alias'];
  686. if (!empty($this->table_queue[$alias])) {
  687. return $this->table_queue[$alias];
  688. }
  689. }
  690. }
  691. /**
  692. * Add a field to the query table, possibly with an alias. This will
  693. * automatically call ensure_table to make sure the required table exists,
  694. * *unless* $table is unset.
  695. *
  696. * @param string $table
  697. * The table this field is attached to. If NULL, it is assumed this will be
  698. * a formula; otherwise, ensure_table is used to make sure the table exists.
  699. * @param string $field
  700. * The name of the field to add. This may be a real field or a formula.
  701. * @param string $alias
  702. * The alias to create. If not specified, the alias will be $table_$field
  703. * unless $table is NULL. When adding formulae, it is recommended that an
  704. * alias be used.
  705. * @param array $params
  706. * An array of parameters additional to the field that will control items
  707. * such as aggregation functions and DISTINCT.
  708. *
  709. * @return string
  710. * The name that this field can be referred to as, usually the alias.
  711. */
  712. public function add_field($table, $field, $alias = '', $params = array()) {
  713. // We check for this specifically because it gets a special alias.
  714. if ($table == $this->base_table && $field == $this->base_field && empty($alias)) {
  715. $alias = $this->base_field;
  716. }
  717. if ($table && empty($this->table_queue[$table])) {
  718. $this->ensure_table($table);
  719. }
  720. if (!$alias && $table) {
  721. $alias = $table . '_' . $field;
  722. }
  723. // Make sure an alias is assigned.
  724. $alias = $alias ? $alias : $field;
  725. // PostgreSQL truncates aliases to 63 characters.
  726. // @see http://drupal.org/node/571548
  727. // We limit the length of the original alias up to 60 characters
  728. // to get a unique alias later if its have duplicates.
  729. $alias = strtolower(substr($alias, 0, 60));
  730. // Create a field info array.
  731. $field_info = array(
  732. 'field' => $field,
  733. 'table' => $table,
  734. 'alias' => $alias,
  735. ) + $params;
  736. // Test to see if the field is actually the same or not. Due to differing
  737. // parameters changing the aggregation function, we need to do some
  738. // automatic alias collision detection.
  739. $base = $alias;
  740. $counter = 0;
  741. while (!empty($this->fields[$alias]) && $this->fields[$alias] != $field_info) {
  742. $field_info['alias'] = $alias = $base . '_' . ++$counter;
  743. }
  744. if (empty($this->fields[$alias])) {
  745. $this->fields[$alias] = $field_info;
  746. }
  747. // Keep track of all aliases used.
  748. $this->field_aliases[$table][$field] = $alias;
  749. return $alias;
  750. }
  751. /**
  752. * Remove all fields that may've been added.
  753. *
  754. * Primarily used for summary mode where we're changing the query because we
  755. * didn't get data we needed.
  756. */
  757. public function clear_fields() {
  758. $this->fields = array();
  759. }
  760. /**
  761. * Add a simple WHERE clause to the query.
  762. *
  763. * The caller is responsible for ensuring that all fields are fully qualified
  764. * (TABLE.FIELD) and that the table already exists in the query.
  765. *
  766. * @param string $group
  767. * The WHERE group to add these to; groups are used to create AND/OR
  768. * sections. Groups cannot be nested. Use 0 as the default group. If the
  769. * group does not yet exist it will be created as an AND group.
  770. * @param string $field
  771. * The name of the field to check.
  772. * @param string $value
  773. * The value to test the field against. In most cases, this is a scalar. For
  774. * more complex options, it is an array. The meaning of each element in the
  775. * array is dependent on the $operator.
  776. * @param string $operator
  777. * The comparison operator, such as =, <, or >=. It also accepts more
  778. * complex options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is
  779. * an array = otherwise. If $field is a string you have to use 'formula'
  780. * here.
  781. *
  782. * The $field, $value and $operator arguments can also be passed in with a
  783. * single DatabaseCondition object, like this:
  784. *
  785. * @code
  786. * $this->query->add_where(
  787. * $this->options['group'],
  788. * db_or()
  789. * ->condition($field, $value, 'NOT IN')
  790. * ->condition($field, $value, 'IS NULL')
  791. * );
  792. * @endcode
  793. *
  794. * @see QueryConditionInterface::condition()
  795. * @see DatabaseCondition
  796. */
  797. public function add_where($group, $field, $value = NULL, $operator = NULL) {
  798. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all the
  799. // default group.
  800. if (empty($group)) {
  801. $group = 0;
  802. }
  803. // Check for a group.
  804. if (!isset($this->where[$group])) {
  805. $this->set_where_group('AND', $group);
  806. }
  807. $this->where[$group]['conditions'][] = array(
  808. 'field' => $field,
  809. 'value' => $value,
  810. 'operator' => $operator,
  811. );
  812. }
  813. /**
  814. * Add a complex WHERE clause to the query.
  815. *
  816. * The caller is responsible for ensuring that all fields are fully qualified
  817. * (TABLE.FIELD) and that the table already exists in the query. Internally
  818. * the dbtng method "where" is used.
  819. *
  820. * @param string $group
  821. * The WHERE group to add these to; groups are used to create AND/OR
  822. * sections. Groups cannot be nested. Use 0 as the default group. If the
  823. * group does not yet exist it will be created as an AND group.
  824. * @param string $snippet
  825. * The snippet to check. This can be either a column or a complex expression
  826. * like "UPPER(table.field) = 'value'".
  827. * @param array $args
  828. * An associative array of arguments.
  829. *
  830. * @see QueryConditionInterface::where()
  831. */
  832. public function add_where_expression($group, $snippet, $args = array()) {
  833. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
  834. // the default group.
  835. if (empty($group)) {
  836. $group = 0;
  837. }
  838. // Check for a group.
  839. if (!isset($this->where[$group])) {
  840. $this->set_where_group('AND', $group);
  841. }
  842. $this->where[$group]['conditions'][] = array(
  843. 'field' => $snippet,
  844. 'value' => $args,
  845. 'operator' => 'formula',
  846. );
  847. }
  848. /**
  849. * Add a simple HAVING clause to the query.
  850. *
  851. * The caller is responsible for ensuring that all fields are fully qualified
  852. * (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist
  853. * in the query. Internally the dbtng method "havingCondition" is used.
  854. *
  855. * @param string $group
  856. * The HAVING group to add these to; groups are used to create AND/OR
  857. * sections. Groups cannot be nested. Use 0 as the default group. If the
  858. * group does not yet exist it will be created as an AND group.
  859. * @param string $field
  860. * The name of the field to check.
  861. * @param string $value
  862. * The value to test the field against. In most cases, this is a scalar. For
  863. * more complex options, it is an array. The meaning of each element in the
  864. * array is dependent on the $operator.
  865. * @param string $operator
  866. * The comparison operator, such as =, <, or >=. It also accepts more
  867. * complex options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is
  868. * an array = otherwise. If $field is a string you have to use 'formula'
  869. * here.
  870. *
  871. * @see SelectQueryInterface::havingCondition()
  872. */
  873. public function add_having($group, $field, $value = NULL, $operator = NULL) {
  874. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all the
  875. // default group.
  876. if (empty($group)) {
  877. $group = 0;
  878. }
  879. // Check for a group.
  880. if (!isset($this->having[$group])) {
  881. $this->set_where_group('AND', $group, 'having');
  882. }
  883. // Add the clause and the args.
  884. $this->having[$group]['conditions'][] = array(
  885. 'field' => $field,
  886. 'value' => $value,
  887. 'operator' => $operator,
  888. );
  889. }
  890. /**
  891. * Add a complex HAVING clause to the query.
  892. *
  893. * The caller is responsible for ensuring that all fields are fully qualified
  894. * (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist
  895. * in the query. Internally the dbtng method "having" is used.
  896. *
  897. * @param string $group
  898. * The HAVING group to add these to; groups are used to create AND/OR
  899. * sections. Groups cannot be nested. Use 0 as the default group. If the
  900. * group does not yet exist it will be created as an AND group.
  901. * @param string $snippet
  902. * The snippet to check. This can be either a column or a complex
  903. * expression like "COUNT(table.field) > 3"
  904. * @param array $args
  905. * An associative array of arguments.
  906. *
  907. * @see QueryConditionInterface::having()
  908. */
  909. public function add_having_expression($group, $snippet, $args = array()) {
  910. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
  911. // the default group.
  912. if (empty($group)) {
  913. $group = 0;
  914. }
  915. // Check for a group.
  916. if (!isset($this->having[$group])) {
  917. $this->set_where_group('AND', $group, 'having');
  918. }
  919. // Add the clause and the args.
  920. $this->having[$group]['conditions'][] = array(
  921. 'field' => $snippet,
  922. 'value' => $args,
  923. 'operator' => 'formula',
  924. );
  925. }
  926. /**
  927. * Add an ORDER BY clause to the query.
  928. *
  929. * @param string $table
  930. * The table this field is part of. If a formula, enter NULL. If you want to
  931. * orderby random use "rand" as table and nothing else.
  932. * @param string $field
  933. * The field or formula to sort on. If already a field, enter NULL and put
  934. * in the alias.
  935. * @param string $order
  936. * Either ASC or DESC.
  937. * @param string $alias
  938. * The alias to add the field as. In SQL, all fields in the order by must
  939. * also be in the SELECT portion. If an $alias isn't specified one will be
  940. * generated for from the $field; however, if the $field is a formula, this
  941. * alias will likely fail.
  942. * @param string $params
  943. * Any params that should be passed through to the add_field.
  944. */
  945. public function add_orderby($table, $field = NULL, $order = 'ASC', $alias = '', $params = array()) {
  946. // Only ensure the table if it's not the special random key.
  947. // @todo Maybe it would make sense to just add a add_orderby_rand or
  948. // something similar.
  949. if ($table && $table != 'rand') {
  950. $this->ensure_table($table);
  951. }
  952. // Only fill out this aliasing if there is a table; otherwise we assume it
  953. // is a formula.
  954. if (!$alias && $table) {
  955. $as = $table . '_' . $field;
  956. }
  957. else {
  958. $as = $alias;
  959. }
  960. if ($field) {
  961. $as = $this->add_field($table, $field, $as, $params);
  962. }
  963. $this->orderby[] = array(
  964. 'field' => $as,
  965. 'direction' => strtoupper($order),
  966. );
  967. }
  968. /**
  969. * Add a simple GROUP BY clause to the query.
  970. *
  971. * The caller is responsible for ensuring that the fields are fully qualified
  972. * and the table is properly added.
  973. */
  974. public function add_groupby($clause) {
  975. // Only add it if it's not already in there.
  976. if (!in_array($clause, $this->groupby)) {
  977. $this->groupby[] = $clause;
  978. }
  979. }
  980. /**
  981. * Returns the alias for the given field added to $table.
  982. *
  983. * @see views_plugin_query_default::add_field()
  984. */
  985. public function get_field_alias($table_alias, $field) {
  986. return isset($this->field_aliases[$table_alias][$field]) ? $this->field_aliases[$table_alias][$field] : FALSE;
  987. }
  988. /**
  989. * Adds a query tag to the sql object.
  990. *
  991. * @see SelectQuery::addTag()
  992. */
  993. public function add_tag($tag) {
  994. $this->tags[] = $tag;
  995. }
  996. /**
  997. * Generates a unique placeholder used in the db query.
  998. */
  999. public function placeholder($base = 'views') {
  1000. static $placeholders = array();
  1001. if (!isset($placeholders[$base])) {
  1002. $placeholders[$base] = 0;
  1003. return ':' . $base;
  1004. }
  1005. else {
  1006. return ':' . $base . ++$placeholders[$base];
  1007. }
  1008. }
  1009. /**
  1010. * Construct the "WHERE" or "HAVING" part of the query.
  1011. *
  1012. * As views has to wrap the conditions from arguments with AND, a special
  1013. * group is wrapped around all conditions. This special group has the ID 0.
  1014. * There is other code in filters which makes sure that the group IDs are
  1015. * higher than zero.
  1016. *
  1017. * @param string $where
  1018. * Either 'where' or 'having'.
  1019. */
  1020. public function build_condition($where = 'where') {
  1021. $has_condition = FALSE;
  1022. $has_arguments = FALSE;
  1023. $has_filter = FALSE;
  1024. $main_group = db_and();
  1025. $filter_group = $this->group_operator == 'OR' ? db_or() : db_and();
  1026. foreach ($this->$where as $group => $info) {
  1027. if (!empty($info['conditions'])) {
  1028. $sub_group = $info['type'] == 'OR' ? db_or() : db_and();
  1029. foreach ($info['conditions'] as $key => $clause) {
  1030. // DBTNG doesn't support to add the same subquery twice to the main
  1031. // query and the count query, so clone the subquery to have two
  1032. // instances of the same object.
  1033. // @see http://drupal.org/node/1112854
  1034. if (is_object($clause['value']) && $clause['value'] instanceof SelectQuery) {
  1035. $clause['value'] = clone $clause['value'];
  1036. }
  1037. if ($clause['operator'] == 'formula') {
  1038. $has_condition = TRUE;
  1039. $sub_group->where($clause['field'], $clause['value']);
  1040. }
  1041. else {
  1042. $has_condition = TRUE;
  1043. $sub_group->condition($clause['field'], $clause['value'], $clause['operator']);
  1044. }
  1045. }
  1046. // Add the item to the filter group.
  1047. if ($group != 0) {
  1048. $has_filter = TRUE;
  1049. $filter_group->condition($sub_group);
  1050. }
  1051. else {
  1052. $has_arguments = TRUE;
  1053. $main_group->condition($sub_group);
  1054. }
  1055. }
  1056. }
  1057. if ($has_filter) {
  1058. $main_group->condition($filter_group);
  1059. }
  1060. if (!$has_arguments && $has_condition) {
  1061. return $filter_group;
  1062. }
  1063. if ($has_arguments && $has_condition) {
  1064. return $main_group;
  1065. }
  1066. }
  1067. /**
  1068. * Build fields array.
  1069. */
  1070. public function compile_fields($fields_array, $query) {
  1071. $non_aggregates = array();
  1072. foreach ($fields_array as $field) {
  1073. $string = '';
  1074. if (!empty($field['table'])) {
  1075. $string .= $field['table'] . '.';
  1076. }
  1077. $string .= $field['field'];
  1078. $fieldname = (!empty($field['alias']) ? $field['alias'] : $string);
  1079. if (!empty($field['distinct'])) {
  1080. throw new Exception("Column-level distinct is not supported anymore.");
  1081. }
  1082. if (!empty($field['count'])) {
  1083. // Retained for compatibility.
  1084. $field['function'] = 'count';
  1085. // It seems there's no way to abstract the table+column reference
  1086. // without adding a field, aliasing, and then using the alias.
  1087. }
  1088. if (!empty($field['function'])) {
  1089. $info = $this->get_aggregation_info();
  1090. if (!empty($info[$field['function']]['method']) && function_exists($info[$field['function']]['method'])) {
  1091. $string = $info[$field['function']]['method']($field['function'], $string);
  1092. $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
  1093. $query->addExpression($string, $fieldname, $placeholders);
  1094. }
  1095. $this->has_aggregate = TRUE;
  1096. }
  1097. // This is a formula, using no tables.
  1098. elseif (empty($field['table'])) {
  1099. if (Database::getConnection()->databaseType() != 'pgsql') {
  1100. $non_aggregates[] = $fieldname;
  1101. }
  1102. elseif (!in_array($fieldname, $non_aggregates)) {
  1103. $non_aggregates[] = $fieldname;
  1104. }
  1105. $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
  1106. $query->addExpression($string, $fieldname, $placeholders);
  1107. }
  1108. elseif ($this->distinct && !in_array($fieldname, $this->groupby)) {
  1109. // d7cx: This code was there, apparently needed for PostgreSQL
  1110. // $string = db_driver() == 'pgsql' ? "FIRST($string)" : $string;
  1111. if (Database::getConnection()->databaseType() == 'pgsql' && !in_array($string, $non_aggregates)) {
  1112. $non_aggregates[] = $string;
  1113. }
  1114. $query->addField(!empty($field['table']) ? $field['table'] : $this->base_table, $field['field'], $fieldname);
  1115. }
  1116. elseif (empty($field['aggregate'])) {
  1117. if (Database::getConnection()->databaseType() != 'pgsql') {
  1118. $non_aggregates[] = $fieldname;
  1119. }
  1120. elseif (!in_array($string, $non_aggregates)) {
  1121. $non_aggregates[] = $string;
  1122. }
  1123. $query->addField(!empty($field['table']) ? $field['table'] : $this->base_table, $field['field'], $fieldname);
  1124. }
  1125. // @todo Remove this old code.
  1126. if (!empty($field['distinct']) && empty($field['function'])) {
  1127. $distinct[] = $string;
  1128. }
  1129. else {
  1130. $fields[] = $string;
  1131. }
  1132. if ($this->get_count_optimized) {
  1133. // We only want the first field in this case.
  1134. break;
  1135. }
  1136. }
  1137. return array(
  1138. $non_aggregates,
  1139. );
  1140. }
  1141. /**
  1142. * Generate a query and a countquery from all of the information supplied
  1143. * to the object.
  1144. *
  1145. * @param bool $get_count
  1146. * Provide a countquery if this is true, otherwise provide a normal query.
  1147. *
  1148. * @return SelectQuery
  1149. * A SelectQuery object.
  1150. */
  1151. public function query($get_count = FALSE) {
  1152. // Check query distinct value.
  1153. if (empty($this->no_distinct) && $this->distinct && !empty($this->fields)) {
  1154. if ($this->pure_distinct === FALSE) {
  1155. $base_field_alias = $this->add_field($this->base_table, $this->base_field);
  1156. $this->add_groupby($base_field_alias);
  1157. }
  1158. $distinct = TRUE;
  1159. }
  1160. // An optimized count query includes just the base field instead of all the
  1161. // fields. Determine of this query qualifies by checking for a groupby or
  1162. // distinct.
  1163. $fields_array = $this->fields;
  1164. if ($get_count && !$this->groupby) {
  1165. foreach ($fields_array as $field) {
  1166. if (!empty($field['distinct']) || !empty($field['function'])) {
  1167. $this->get_count_optimized = FALSE;
  1168. break;
  1169. }
  1170. }
  1171. }
  1172. else {
  1173. $this->get_count_optimized = FALSE;
  1174. }
  1175. if (!isset($this->get_count_optimized)) {
  1176. $this->get_count_optimized = TRUE;
  1177. }
  1178. $options = array();
  1179. $target = 'default';
  1180. $key = 'default';
  1181. // Detect an external database and set the.
  1182. if (isset($this->view->base_database)) {
  1183. $key = $this->view->base_database;
  1184. }
  1185. // Set the slave target if the slave option is set.
  1186. if (!empty($this->options['slave'])) {
  1187. $target = 'slave';
  1188. }
  1189. // Go ahead and build the query. db_select doesn't support to specify the
  1190. // key, so use getConnection directly.
  1191. $query = Database::getConnection($target, $key)
  1192. ->select($this->base_table, $this->base_table, $options)
  1193. ->addTag('views')
  1194. ->addTag('views_' . $this->view->name);
  1195. // Add the tags added to the view itself.
  1196. foreach ($this->tags as $tag) {
  1197. $query->addTag($tag);
  1198. }
  1199. if (!empty($distinct)) {
  1200. $query->distinct();
  1201. }
  1202. $joins = $where = $having = $orderby = $groupby = '';
  1203. $fields = $distinct = array();
  1204. // Add all the tables to the query via joins. We assume all LEFT joins.
  1205. foreach ($this->table_queue as $table) {
  1206. if (is_object($table['join'])) {
  1207. $table['join']->build_join($query, $table, $this);
  1208. }
  1209. }
  1210. $this->has_aggregate = FALSE;
  1211. $non_aggregates = array();
  1212. list($non_aggregates) = $this->compile_fields($fields_array, $query);
  1213. if (count($this->having)) {
  1214. $this->has_aggregate = TRUE;
  1215. }
  1216. // Allow 'GROUP BY' even if no aggregation function has been set, but only
  1217. // when there is a legitimate display_handler.
  1218. elseif (!$this->has_aggregate && !empty($this->view->display_handler)) {
  1219. $this->has_aggregate = $this->view->display_handler->get_option('group_by');
  1220. }
  1221. if ($this->has_aggregate && (!empty($this->groupby) || !empty($non_aggregates))) {
  1222. $groupby = array_unique(array_merge($this->groupby, $non_aggregates));
  1223. foreach ($groupby as $field) {
  1224. $query->groupBy($field);
  1225. }
  1226. if (!empty($this->having) && $condition = $this->build_condition('having')) {
  1227. $query->havingCondition($condition);
  1228. }
  1229. }
  1230. if (!$this->get_count_optimized) {
  1231. // We only add the orderby if we're not counting.
  1232. if ($this->orderby) {
  1233. foreach ($this->orderby as $order) {
  1234. if ($order['field'] == 'rand_') {
  1235. $query->orderRandom();
  1236. }
  1237. else {
  1238. $query->orderBy($order['field'], $order['direction']);
  1239. }
  1240. }
  1241. }
  1242. }
  1243. if (!empty($this->where) && $condition = $this->build_condition('where')) {
  1244. $query->condition($condition);
  1245. }
  1246. // Add a query comment.
  1247. if (!empty($this->options['query_comment'])) {
  1248. $query->comment($this->options['query_comment']);
  1249. }
  1250. // Add the query tags.
  1251. if (!empty($this->options['query_tags'])) {
  1252. foreach ($this->options['query_tags'] as $tag) {
  1253. $query->addTag($tag);
  1254. }
  1255. }
  1256. // Add all query substitutions as metadata.
  1257. $query->addMetaData('views_substitutions', module_invoke_all('views_query_substitutions', $this->view));
  1258. if (!$get_count) {
  1259. if (!empty($this->limit) || !empty($this->offset)) {
  1260. // We can't have an offset without a limit, so provide a very large
  1261. // limit instead.
  1262. $limit = intval(!empty($this->limit) ? $this->limit : 999999);
  1263. $offset = intval(!empty($this->offset) ? $this->offset : 0);
  1264. $query->range($offset, $limit);
  1265. }
  1266. }
  1267. return $query;
  1268. }
  1269. /**
  1270. * Get the arguments attached to the WHERE and HAVING clauses of this query.
  1271. */
  1272. public function get_where_args() {
  1273. $args = array();
  1274. foreach ($this->where as $group => $where) {
  1275. $args = array_merge($args, $where['args']);
  1276. }
  1277. foreach ($this->having as $group => $having) {
  1278. $args = array_merge($args, $having['args']);
  1279. }
  1280. return $args;
  1281. }
  1282. /**
  1283. * Let modules modify the query just prior to finalizing it.
  1284. */
  1285. public function alter(&$view) {
  1286. foreach (module_implements('views_query_alter') as $module) {
  1287. $function = $module . '_views_query_alter';
  1288. $function($view, $this);
  1289. }
  1290. }
  1291. /**
  1292. * Builds the necessary info to execute the query.
  1293. */
  1294. public function build(&$view) {
  1295. // Make the query distinct if the option was set.
  1296. if (!empty($this->options['distinct'])) {
  1297. $this->set_distinct(TRUE, !empty($this->options['pure_distinct']));
  1298. }
  1299. // Store the view in the object to be able to use it later.
  1300. $this->view = $view;
  1301. $view->init_pager();
  1302. // Let the pager modify the query to add limits.
  1303. $this->pager->query();
  1304. $view->build_info['query'] = $this->query();
  1305. $view->build_info['count_query'] = $this->query(TRUE);
  1306. }
  1307. /**
  1308. * Executes the query and fills the associated view object with according
  1309. * values.
  1310. *
  1311. * Values to set: $view->result, $view->total_rows, $view->execute_time,
  1312. * $view->current_page.
  1313. */
  1314. public function execute(&$view) {
  1315. // Whether this query will run against an external database.
  1316. $external = FALSE;
  1317. $query = $view->build_info['query'];
  1318. $count_query = $view->build_info['count_query'];
  1319. $query->addMetaData('view', $view);
  1320. $count_query->addMetaData('view', $view);
  1321. if (empty($this->options['disable_sql_rewrite'])) {
  1322. $base_table_data = views_fetch_data($this->base_table);
  1323. if (isset($base_table_data['table']['base']['access query tag'])) {
  1324. $access_tag = $base_table_data['table']['base']['access query tag'];
  1325. $query->addTag($access_tag);
  1326. $count_query->addTag($access_tag);
  1327. }
  1328. }
  1329. $items = array();
  1330. if ($query) {
  1331. $additional_arguments = module_invoke_all('views_query_substitutions', $view);
  1332. // Count queries must be run through the preExecute() method.
  1333. // If not, then hook_query_node_access_alter() may munge the count by
  1334. // adding a distinct against an empty query string
  1335. // (e.g. COUNT DISTINCT(1) ...) and no pager will return.
  1336. // @see pager.inc > PagerDefault::execute()
  1337. // @see http://api.drupal.org/api/drupal/includes--pager.inc/function/PagerDefault::execute/7
  1338. // @see http://drupal.org/node/1046170.
  1339. $count_query->preExecute();
  1340. // Build the count query.
  1341. $count_query = $count_query->countQuery();
  1342. // Add additional arguments as a fake condition.
  1343. // XXX: this doesn't work... because PDO mandates that all bound arguments
  1344. // are used on the query. TODO: Find a better way to do this.
  1345. if (!empty($additional_arguments)) {
  1346. // $query->where('1 = 1', $additional_arguments);
  1347. // $count_query->where('1 = 1', $additional_arguments);
  1348. }
  1349. $start = microtime(TRUE);
  1350. try {
  1351. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  1352. $this->pager->execute_count_query($count_query);
  1353. }
  1354. $this->pager->pre_execute($query);
  1355. $result = $query->execute();
  1356. $view->result = array();
  1357. foreach ($result as $item) {
  1358. $view->result[] = $item;
  1359. }
  1360. $this->pager->post_execute($view->result);
  1361. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  1362. $view->total_rows = $this->pager->get_total_items();
  1363. }
  1364. }
  1365. catch (Exception $e) {
  1366. $view->result = array();
  1367. if (!empty($view->live_preview)) {
  1368. drupal_set_message($e->getMessage(), 'error');
  1369. }
  1370. else {
  1371. vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
  1372. }
  1373. }
  1374. }
  1375. else {
  1376. $start = microtime(TRUE);
  1377. }
  1378. $view->execute_time = microtime(TRUE) - $start;
  1379. }
  1380. /**
  1381. *
  1382. */
  1383. public function add_signature(&$view) {
  1384. $view->query->add_field(NULL, "'" . $view->name . ':' . $view->current_display . "'", 'view_name');
  1385. }
  1386. /**
  1387. *
  1388. */
  1389. public function get_aggregation_info() {
  1390. // @todo Need a way to get database specific and customized aggregation
  1391. // functions into here.
  1392. return array(
  1393. 'group' => array(
  1394. 'title' => t('Group results together'),
  1395. 'is aggregate' => FALSE,
  1396. ),
  1397. 'count' => array(
  1398. 'title' => t('Count'),
  1399. 'method' => 'views_query_default_aggregation_method_simple',
  1400. 'handler' => array(
  1401. 'argument' => 'views_handler_argument_group_by_numeric',
  1402. 'field' => 'views_handler_field_numeric',
  1403. 'filter' => 'views_handler_filter_group_by_numeric',
  1404. 'sort' => 'views_handler_sort_group_by_numeric',
  1405. ),
  1406. ),
  1407. 'count_distinct' => array(
  1408. 'title' => t('Count DISTINCT'),
  1409. 'method' => 'views_query_default_aggregation_method_distinct',
  1410. 'handler' => array(
  1411. 'argument' => 'views_handler_argument_group_by_numeric',
  1412. 'field' => 'views_handler_field_numeric',
  1413. 'filter' => 'views_handler_filter_group_by_numeric',
  1414. 'sort' => 'views_handler_sort_group_by_numeric',
  1415. ),
  1416. ),
  1417. 'sum' => array(
  1418. 'title' => t('Sum'),
  1419. 'method' => 'views_query_default_aggregation_method_simple',
  1420. 'handler' => array(
  1421. 'argument' => 'views_handler_argument_group_by_numeric',
  1422. 'filter' => 'views_handler_filter_group_by_numeric',
  1423. 'sort' => 'views_handler_sort_group_by_numeric',
  1424. ),
  1425. ),
  1426. 'avg' => array(
  1427. 'title' => t('Average'),
  1428. 'method' => 'views_query_default_aggregation_method_simple',
  1429. 'handler' => array(
  1430. 'argument' => 'views_handler_argument_group_by_numeric',
  1431. 'filter' => 'views_handler_filter_group_by_numeric',
  1432. 'sort' => 'views_handler_sort_group_by_numeric',
  1433. ),
  1434. ),
  1435. 'min' => array(
  1436. 'title' => t('Minimum'),
  1437. 'method' => 'views_query_default_aggregation_method_simple',
  1438. 'handler' => array(
  1439. 'argument' => 'views_handler_argument_group_by_numeric',
  1440. 'filter' => 'views_handler_filter_group_by_numeric',
  1441. 'sort' => 'views_handler_sort_group_by_numeric',
  1442. ),
  1443. ),
  1444. 'max' => array(
  1445. 'title' => t('Maximum'),
  1446. 'method' => 'views_query_default_aggregation_method_simple',
  1447. 'handler' => array(
  1448. 'argument' => 'views_handler_argument_group_by_numeric',
  1449. 'filter' => 'views_handler_filter_group_by_numeric',
  1450. 'sort' => 'views_handler_sort_group_by_numeric',
  1451. ),
  1452. ),
  1453. 'stddev_pop' => array(
  1454. 'title' => t('Standard deviation'),
  1455. 'method' => 'views_query_default_aggregation_method_simple',
  1456. 'handler' => array(
  1457. 'argument' => 'views_handler_argument_group_by_numeric',
  1458. 'filter' => 'views_handler_filter_group_by_numeric',
  1459. 'sort' => 'views_handler_sort_group_by_numeric',
  1460. ),
  1461. ),
  1462. ) + views_fetch_plugin_data('query_aggregate');
  1463. }
  1464. /**
  1465. * Returns the according entity objects for the given query results.
  1466. */
  1467. public function get_result_entities($results, $relationship = NULL) {
  1468. $base_table = $this->base_table;
  1469. $base_table_alias = $base_table;
  1470. if (!empty($relationship)) {
  1471. foreach ($this->view->relationship as $current) {
  1472. if ($current->alias == $relationship) {
  1473. $base_table = $current->definition['base'];
  1474. $base_table_alias = $relationship;
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. $table_data = views_fetch_data($base_table);
  1480. // Bail out if the table has not specified the according entity-type.
  1481. if (!isset($table_data['table']['entity type'])) {
  1482. return FALSE;
  1483. }
  1484. $entity_type = $table_data['table']['entity type'];
  1485. $info = entity_get_info($entity_type);
  1486. $is_revision = !empty($table_data['table']['revision']);
  1487. $id_alias = $this->get_field_alias($base_table_alias, $info['entity keys'][$is_revision ? 'revision' : 'id']);
  1488. // Assemble the ids of the entities to load.
  1489. $ids = array();
  1490. foreach ($results as $key => $result) {
  1491. if (isset($result->$id_alias)) {
  1492. $ids[$key] = $result->$id_alias;
  1493. }
  1494. }
  1495. if (!$is_revision) {
  1496. $entities = entity_load($entity_type, $ids);
  1497. // Re-key the array by row-index.
  1498. $result = array();
  1499. foreach ($ids as $key => $id) {
  1500. $result[$key] = isset($entities[$id]) ? $entities[$id] : FALSE;
  1501. }
  1502. }
  1503. else {
  1504. // There's no way in core to load revisions in bulk.
  1505. $result = array();
  1506. foreach ($ids as $key => $id) {
  1507. // Nodes can be dealt with in core.
  1508. if ($entity_type == 'node') {
  1509. $result[$key] = node_load(NULL, $id);
  1510. }
  1511. // Otherwise see if entity is enabled.
  1512. elseif (module_exists('entity')) {
  1513. $result[$key] = entity_revision_load($entity_type, $id);
  1514. }
  1515. else {
  1516. // Otherwise this isn't supported.
  1517. watchdog('views', 'Attempt to load a revision on an unsupported entity type @entity_type.', array('@entity_type' => $entity_type), WATCHDOG_WARNING);
  1518. }
  1519. }
  1520. }
  1521. return array($entity_type, $result);
  1522. }
  1523. }
  1524. /**
  1525. *
  1526. */
  1527. function views_query_default_aggregation_method_simple($group_type, $field) {
  1528. return strtoupper($group_type) . '(' . $field . ')';
  1529. }
  1530. /**
  1531. *
  1532. */
  1533. function views_query_default_aggregation_method_distinct($group_type, $field) {
  1534. $group_type = str_replace('_distinct', '', $group_type);
  1535. return strtoupper($group_type) . '(DISTINCT ' . $field . ')';
  1536. }
  1537. /**
  1538. * Validation callback for query tags.
  1539. */
  1540. function views_element_validate_tags($element, &$form_state) {
  1541. $values = array_map('trim', explode(',', $element['#value']));
  1542. foreach ($values as $value) {
  1543. if (preg_match("/[^a-z_]/", $value)) {
  1544. form_error($element, t('The query tags may only contain lower-case alphabetical characters and underscores.'));
  1545. return;
  1546. }
  1547. }
  1548. }