views_handler_join_chado_aggregator.inc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. /**
  3. * @file
  4. * Handler to allow joins between records via a linking table
  5. *
  6. * Example Usage:
  7. * To join the analysisprop table to the analysis table,
  8. * Use the following code in the analysisprop hook_views_data:
  9. * @code
  10. $data['analysisprop']['table']['join']['analysis'] = array(
  11. 'left_field' => 'analysis_id',
  12. 'field' => 'analysis_id',
  13. 'handler' => 'views_handler_join_chado_aggregator',
  14. 'pre-aggregated' => TRUE | FALSE //whether the table is already aggregated (contains arrays)
  15. 'table_aggregated' => CURRENT | LEFT //the table which has many records for each record in the other
  16. );
  17. * @endcode
  18. */
  19. class views_handler_join_chado_aggregator extends views_join {
  20. // PHP 4 doesn't call constructors of the base class automatically from a
  21. // constructor of a derived class. It is your responsibility to propagate
  22. // the call to constructors upstream where appropriate.
  23. function construct($table = NULL, $left_table = NULL, $left_field = NULL, $field = NULL, $extra = array(), $type = 'LEFT', $added = NULL) {
  24. parent::construct($table, $left_table, $left_field, $field, $extra, $type);
  25. // Determine the postgresql version
  26. $postgresql_version = pg_version();
  27. $this->postgresql_version = $postgresql_version['client'];
  28. // If version is 9.0+ then indicate
  29. // Needed to apply sorting for aggregated fields
  30. if (intval($postgresql_version['client']) >= 9) {
  31. $this->postgresql_9up = TRUE;
  32. }
  33. }
  34. /**
  35. * Creates SQL including aggregation query used in join
  36. */
  37. function join($table, &$query) {
  38. $output = array();
  39. // Create the table SQL (used in join) -------
  40. // query creating one-to-one table using array_agg
  41. // Only aggregate each field if it the join table hadn't been pre-aggregated
  42. // Example where it might be pre-aggregated: Materialized view
  43. if (!$this->definition['pre-aggregated']) {
  44. // Determine Order BY's for aggregates
  45. $order_by = array();
  46. if (!is_array($this->sort)) { $this->sort = array(); }
  47. foreach ($this->sort as $s) {
  48. $order_by[] = $s['table'].'.'.$s['field'].' '.$s['order'];
  49. }
  50. // get table description (if defined via schema api)
  51. $table_desc = module_invoke_all('chado_'.$this->definition['table'].'_schema');
  52. $select_fields[ $this->definition['table'] ] = $table_desc['fields'];
  53. if (!empty($table_desc)) {
  54. // Add joins to tables with a foreign key in this table
  55. // (ie: add join to cvterm if this table has a type_id
  56. $joins = array();
  57. foreach($table_desc['foreign keys'] as $defn) {
  58. if ($defn['table'] != $this->left_table) {
  59. foreach( $defn['columns'] as $left => $right) {
  60. $left = $this->definition['table'] .'.'. $left;
  61. $right = $defn[table] .'.'. $right;
  62. $joins[] = "LEFT JOIN $defn[table] $defn[table] ON $left=$right";
  63. }
  64. // Fields to be selected from joined table
  65. $join_table = module_invoke_all('chado_'.$defn['table'].'_schema');
  66. $select_fields[ $defn['table'] ] = $join_table['fields'];
  67. }
  68. }
  69. // Fields to be selected
  70. foreach ($select_fields as $table => $table_fields) {
  71. foreach ($table_fields as $fname => $f) {
  72. $alias = '';
  73. if ($table != $this->definition['table']) {
  74. $alias = $table .'_';
  75. }
  76. if ($fname != $this->definition['field']) {
  77. // Add sort to aggregate field if postgreSQL 9.0+
  78. if ($this->postgresql_9up && !empty($order_by)) {
  79. $fields[] = 'array_agg('.$table.'.'.$fname.' ORDER BY '.implode(',',$order_by).') as '.$alias.$fname;
  80. } else {
  81. $fields[] = 'array_agg('.$table.'.'.$fname.') as '.$alias.$fname;
  82. }
  83. $composite_field_parts[] = "'".$alias.$fname."::' ||".$table.'.'.$fname;
  84. } else {
  85. $fields[] = $fname;
  86. $composite_field_parts[] = "'".$alias.$fname."::' ||".$table.'.'.$fname;
  87. }
  88. }
  89. }
  90. // There is no definition in schema api
  91. // then use postgresql select
  92. } else {
  93. // No known foreign key reelationships
  94. $joins = array();
  95. // Fields to be selected
  96. $sql = "SELECT
  97. attname as column,
  98. format_type(atttypid, atttypmod) as datatype
  99. FROM pg_attribute, pg_type
  100. WHERE typname='nd_genotype_experiment'
  101. AND attrelid=typrelid
  102. AND attname NOT IN ('cmin','cmax','ctid','oid','tableoid','xmin','xmax')";
  103. $previous_db = tripal_db_set_active('chado');
  104. $resource = db_query($sql);
  105. tripal_db_set_active($previous_db);
  106. while ($r = db_fetch_object($resource)) {
  107. $table = $this->definition['table'];
  108. $alias = ''; //no alias needed if table is current table (only option if no schema api definition)
  109. $fname = $r->column;
  110. if ($fname != $this->definition['field']) {
  111. // Add sort to aggregate field if postgreSQL 9.0+
  112. if ($this->postgresql_9up && !empty($order_by)) {
  113. $fields[] = 'array_agg('.$table.'.'.$fname.' ORDER BY '.implode(',',$order_by).') as '.$alias.$fname;
  114. } else {
  115. $fields[] = 'array_agg('.$table.'.'.$fname.') as '.$alias.$fname;
  116. }
  117. $composite_field_parts[] = "'".$alias.$fname."::' ||".$table.'.'.$fname;
  118. } else {
  119. $fields[] = $fname;
  120. $composite_field_parts[] = "'".$alias.$fname."::' ||".$table.'.'.$fname;
  121. }
  122. }
  123. }
  124. // composite field
  125. // (combines all other fields before aggregating)
  126. // Add sort to aggregate field if postgreSQL 9.0+
  127. if ($this->postgresql_9up && !empty($order_by)) {
  128. $composite_field = "array_agg('{'||".implode(" || ',' || ",$composite_field_parts)."||'}' ORDER BY ".implode(',',$order_by).") as all";
  129. } else {
  130. $composite_field = "array_agg('{'||".implode(" || ',' || ",$composite_field_parts)."||'}') as all";
  131. }
  132. $fields[] = $composite_field;
  133. // SQL to use in the join
  134. $sql = 'SELECT '.implode(', ',$fields)
  135. .' FROM '.$this->definition['table']
  136. .' '.implode(' ',$joins);
  137. if (!empty($this->filter)) {
  138. $sql .= ' WHERE '.implode(', ', $this->filter);
  139. }
  140. $sql .= ' GROUP BY '.$this->definition['field'];
  141. // Create the join (full SQL) ----------------
  142. $output[] = $this->create_single_join(
  143. $query,
  144. array(
  145. 'table' => $this->definition['table'],
  146. 'field' => $this->definition['field'],
  147. 'table_sql' => $sql,
  148. 'is_drupal' => FALSE,
  149. ),
  150. array(
  151. 'table' => $this->definition['left_table'],
  152. 'field' => $this->definition['left_field'],
  153. ),
  154. 'LEFT'
  155. );
  156. // Otherwise the table has been pre-aggregated
  157. // Then only need to do a regular join with any in where
  158. } else {
  159. // Create the join
  160. $current_table_spec = array(
  161. 'table' => $this->definition['table'],
  162. 'field' => $this->definition['field'],
  163. 'is_drupal' => FALSE,
  164. );
  165. $left_table_spec = array(
  166. 'table' => $this->definition['left_table'],
  167. 'field' => $this->definition['left_field'],
  168. );
  169. switch ($this->definition['table_aggregated']) {
  170. default:
  171. case 'CURRENT':
  172. $current_table_spec['pre-aggregated'] = TRUE;
  173. break;
  174. case 'LEFT':
  175. $left_table_spec['pre-aggregated'] = TRUE;
  176. break;
  177. }
  178. $output[] = $this->create_single_join(
  179. $query,
  180. $current_table_spec,
  181. $left_table_spec,
  182. 'LEFT'
  183. );
  184. }
  185. return implode("\n",$output);
  186. }
  187. /**
  188. * Creates SQL for a single join based on parameters
  189. * Join will be: <type> JOIN (<query creating one-to-one table using array_agg>) <table alias>
  190. * ON <qualified left field>=<qualified right field>
  191. */
  192. function create_single_join(&$query, $right_spec, $left_spec, $join_type) {
  193. if ($right_spec['table']) {
  194. $right = $query->get_table_info($right_spec['table']);
  195. if (!$right['alias']) {
  196. $right['alias'] = $right_spec['table'];
  197. }
  198. $right_field = "$right[alias].$right_spec[field]";
  199. // Add any() around field if already aggregated
  200. if ($right_spec['pre-aggregated']) {
  201. $right_field = "any(".$right_field.")";
  202. }
  203. // Add drupal { } around table
  204. if ($right_spec['is_drupal']) {
  205. $right_table = '{' . $right_spec['table'] . '}';
  206. }
  207. else {
  208. $right_table = $right_spec['table'];
  209. }
  210. }
  211. if ($left_spec['table']) {
  212. $left = $query->get_table_info($left_spec['table']);
  213. if (!$left['alias']) {
  214. $left['alias'] = $left_spec['table'];
  215. }
  216. $left_field = "$left[alias].$left_spec[field]";
  217. }
  218. else {
  219. // This can be used if left_field is a formula or something. It should be used only *very* rarely.
  220. $left_field = $this->left_spec['field'];
  221. }
  222. // Add any() around field if already aggregated
  223. if ($left_spec['pre-aggregated']) {
  224. $left_field = "any(".$left_field.")";
  225. }
  226. // Concatenate parts together to form join sql
  227. if (!empty($right_spec[table_sql])) {
  228. $output = " $join_type JOIN ($right_spec[table_sql]) $right[alias] ON $left_field = $right_field";
  229. } else {
  230. $output = " $join_type JOIN $right_spec[table] $right[alias] ON $left_field = $right_field";
  231. }
  232. return $output;
  233. }
  234. }