ChadoField.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. <?php
  2. class ChadoField extends TripalField {
  3. // The default lable for this field.
  4. public static $default_label = 'Chado Field';
  5. // The default description for this field.
  6. public static $default_description = 'The generic base class for all Chado fields. Replace this text as appropriate for the child implementation.';
  7. // A list of global settings. These can be accessed within the
  8. // globalSettingsForm. When the globalSettingsForm is submitted then
  9. // Drupal will automatically change these settings for all fields.
  10. // Once instances exist for a field type then these settings cannot be
  11. // changed.
  12. public static $default_settings = array(
  13. 'storage' => 'field_chado_storage',
  14. );
  15. // Provide a list of instance specific settings. These can be access within
  16. // the instanceSettingsForm. When the instanceSettingsForm is submitted
  17. // then Drupal with automatically change these settings for the instnace.
  18. // It is recommended to put settings at the instance level whenever possible.
  19. // If you override this variable in a child class be sure to replicate the
  20. // term_name, term_vocab, term_accession and term_fixed keys as these are
  21. // required for all TripalFields.
  22. public static $default_instance_settings = array(
  23. // The short name for the vocabulary (e.g. shcema, SO, GO, PATO, etc.).
  24. 'term_vocabulary' => 'schema',
  25. // The name of the term.
  26. 'term_name' => 'Thing',
  27. // The unique ID (i.e. accession) of the term.
  28. 'term_accession' => 'Thing',
  29. // Set to TRUE if the site admin is allowed to change the term
  30. // type. This will create form elements when editing the field instance
  31. // to allow the site admin to change the term settings above.
  32. 'term_fixed' => FALSE,
  33. // The table in Chado that the instance maps to.
  34. 'chado_table' => '',
  35. // The column of the table in Chado where the value of the field comes from.
  36. 'chado_column' => '',
  37. // The base table.
  38. 'base_table' => '',
  39. );
  40. // Indicates the download formats for this field. The list must be the
  41. // name of a child class of the TripalFieldDownloader.
  42. public static $download_formatters = array(
  43. 'TripalTabDownloader',
  44. 'TripalCSVDownloader',
  45. );
  46. // The module that manages this field.
  47. public static $module = 'tripal_chado';
  48. /**
  49. * @see TripalField::query()
  50. *
  51. * In addition to the rules to follow for the TripalField::query function
  52. * these should also be followed for the ChadoField::query implementation.
  53. *
  54. * - When giving alias to joined tables be sure to use aliases that are
  55. * unique to avoid conflicts with other fields.
  56. * - When joining with the base table its alias is 'base'.
  57. * - You may join to materialized views if need be to help speed queries.
  58. */
  59. public function query($query, $condition) {
  60. // If we are here it is because the child class did not implement the
  61. // query function. So, we will do our best to make the query work.
  62. $chado_table = $this->instance['settings']['chado_table'];
  63. $base_table = $this->instance['settings']['base_table'];
  64. $bschema = chado_get_schema($base_table);
  65. $bpkey = $bschema['primary key'][0];
  66. $alias = 'dbx_linker';
  67. $operator = $condition['operator'];
  68. // If the chado_table and the base_table are the same then this is easy.
  69. if ($chado_table == $base_table) {
  70. // Get the base table column that is associated with the term
  71. // passed as $condition['column'].
  72. $base_field = chado_get_semweb_column($chado_table, $condition['column']);
  73. $query->condition('base.' . $base_field , $condition['value'], $operator);
  74. }
  75. else {
  76. // If the two are not the same then we expect that the child class
  77. // will implement a query() function.
  78. }
  79. }
  80. /**
  81. * @see TripalField::queryOrder()
  82. */
  83. public function queryOrder($query, $order) {
  84. // If we are here it is because the child class did not implement the
  85. // queryOrder function. So, we will do our best to make the query work.
  86. $chado_table = $this->instance['settings']['chado_table'];
  87. $base_table = $this->instance['settings']['base_table'];
  88. $bschema = chado_get_schema($base_table);
  89. $bpkey = $bschema['primary key'][0];
  90. $alias = 'dbx_linker';
  91. $operator = $condition['operator'];
  92. // If the chado_table and the base_table are the same then this is easy.
  93. if ($chado_table == $base_table) {
  94. // Get the base table column that is associated with the term
  95. // passed as $condition['column'].
  96. $base_field = chado_get_semweb_column($chado_table, $order['column']);
  97. $query->orderBy('base.' . $base_field, $order['direction']);
  98. }
  99. else {
  100. // If the two are not the same then we expect that the child class
  101. // will implement a query() function.
  102. }
  103. }
  104. /**
  105. * A convient way to join a table to a query without duplicates.
  106. *
  107. * @param $query
  108. * The SelectQuery object.
  109. * @param $table
  110. * The table to join.
  111. * @param $alias
  112. * The table alias to use.
  113. * @param $condition
  114. * The join condition.
  115. * @param $type
  116. * The type of join: INNER, LEFT OUTER, or RIGHT OUTER.
  117. */
  118. protected function queryJoinOnce($query, $table, $alias, $condition, $type = 'INNER') {
  119. $joins = $query->getTables();
  120. // If this join is already present then don't add it again.
  121. if (in_array($alias, array_keys($joins))) {
  122. return;
  123. }
  124. switch($type) {
  125. case 'LEFT OUTER':
  126. $query->leftjoin($table, $alias, $condition);
  127. break;
  128. case 'RIGHT OUTER':
  129. $query->rightjoin($table, $alias, $condition);
  130. break;
  131. default:
  132. $query->innerjoin($table, $alias, $condition);
  133. }
  134. }
  135. /**
  136. * Used to retrieve a distinct list of values already used for the current field instance.
  137. *
  138. * @param $keyword
  139. * A string option used to filter the distinct list. This is used when creating an
  140. * autocomplete. For all distinct values, set this to NULL.
  141. * @param $options
  142. * An array where options for how to generate this list can be specified.
  143. * Supported options include:
  144. * - limit: how many results to limit to (Default: 25)
  145. * - label_string: a string with tokens that should be used to generate the
  146. * human-readable values in the returned list.
  147. *
  148. * The following example shows you how to pull all the value list for a specific instance
  149. * of a field.
  150. * @code
  151. // In this example we want the values for the obi__organism field
  152. // attached to the Tripal Content Type with a machine name of bio_data_17:
  153. $field_name = 'obi__organism';
  154. $bundle_name = 'bio_data_17';
  155. // The following two calls get information about the field we want the values for.
  156. $field_info = field_info_field($field_name);
  157. $instance_info = field_info_instance('TripalEntity', $field_name, $bundle_name);
  158. // Construct the Field instance we want the values for.
  159. $instance = new ChadoField($field_info, $instance_info);
  160. // Retrieve the values.
  161. // $values will be an array containing the distinct set of values for this field instance.
  162. $values = $instance->getValueList();
  163. * @endcode
  164. *
  165. * @return
  166. * An array of values.
  167. */
  168. public function getValueList($options = array(), $keyword = NULL) {
  169. $values = array();
  170. // Set some defaults.
  171. $options['limit'] = (isset($options['limit'])) ? $options['limit'] : 25;
  172. $options['label_string'] = (isset($options['label_string'])) ? $options['label_string'] : '';
  173. // Make sure we know the chado table and column.
  174. // If not, we can't give them a list *shrugs*.
  175. if (!isset($this->instance['settings']['chado_table']) OR !isset($this->instance['settings']['chado_column'])) {
  176. tripal_report_error(
  177. 'TripalField',
  178. TRIPAL_WARNING,
  179. 'Values List: Unable to generate a values list for %field_name since we don\'t know it\'s chado table/column.',
  180. array('%field_name' => $this->instance['field_name'])
  181. );
  182. return FALSE;
  183. }
  184. // First get some important info about the chado table.column this field is attached to.
  185. $chado_table = $this->instance['settings']['chado_table'];
  186. $chado_column = $this->instance['settings']['chado_column'];
  187. $base_table = $this->instance['settings']['base_table'];
  188. $bschema = chado_get_schema($base_table);
  189. // Now build the distinct query.
  190. if ($chado_table == $base_table) {
  191. // Is the current column a foreign key to another table?
  192. $is_fk = FALSE;
  193. $fk_table = $fk_column = NULL;
  194. foreach ($bschema['foreign keys'] as $k => $v) {
  195. if (isset($v['columns'][$chado_column])) {
  196. $is_fk = TRUE;
  197. $fk_table = $v['table'];
  198. $fk_column = $v['columns'][$chado_column];
  199. }
  200. }
  201. // Check if this column is a foreign key to another one.
  202. // If so we would like to travel through the relationship
  203. // to capture a better human-readable option.
  204. if ($is_fk) {
  205. // Determine the query.
  206. $sql = "SELECT base.$chado_column as id, fk.*
  207. FROM {".$chado_table."} base
  208. LEFT JOIN {".$fk_table."} fk ON base.$chado_column=fk.$fk_column
  209. GROUP BY base.$chado_column, fk.$fk_column
  210. LIMIT ".$options['limit'];
  211. // Choose a default label string, if needed.
  212. if (empty($options['label_string'])) {
  213. $fkschema = chado_get_schema($fk_table);
  214. if (isset($fkschema['fields']['name'])) {
  215. $options['label_string'] = '[name]';
  216. }
  217. elseif (isset($fkschema['fields']['uniquename'])) {
  218. $options['label_string'] = '[uniquename]';
  219. }
  220. elseif (isset($fkschema['fields']['accession'])) {
  221. $options['label_string'] = '[accession]';
  222. }
  223. elseif (isset($fkschema['fields']['title'])) {
  224. $options['label_string'] = '[title]';
  225. }
  226. elseif ($fk_table == 'organism') {
  227. $options['label_string'] = '[genus] [species]';
  228. }
  229. else {
  230. tripal_report_error(
  231. 'TripalField',
  232. TRIPAL_WARNING,
  233. 'Values List: Unable to generate a default human-readable label for %field_name since there is no name/uniquename column. Please set the options[label_string].',
  234. array('%field_name' => $this->instance['field_name'])
  235. );
  236. return FALSE;
  237. }
  238. }
  239. }
  240. // Not a foreign key, so just make the key and value from the base table.
  241. else {
  242. $sql = "SELECT $chado_column as id, $chado_column
  243. FROM {".$chado_table."} base
  244. GROUP BY $chado_column
  245. LIMIT ".$options['limit'];
  246. // Choose a default label string, if needed.
  247. if (empty($options['label_string'])) {
  248. $options['label_string'] = '[' . $chado_column . ']';
  249. }
  250. }
  251. }
  252. else {
  253. tripal_report_error(
  254. 'TripalField',
  255. TRIPAL_WARNING,
  256. 'Unable to retrieve a values list for %field_name since it is not a direct column in %base',
  257. array('%field_name' => $this->instance['field_name'], '%base' => $base_table)
  258. );
  259. return FALSE;
  260. }
  261. $results = chado_query($sql);
  262. // Pre-process the label string for better performance.
  263. // Each token is enclosed in square brackets and should be the name of a chado column.
  264. preg_match_all('/\[(\w+)\]/', $options['label_string'], $matches);
  265. $tokens = $matches[1];
  266. foreach ($results as $r) {
  267. // Determine the label using the label_string option.
  268. $label = $options['label_string'];
  269. $replace = array();
  270. foreach ($tokens as $column) {
  271. if (isset($r->{$column})) {
  272. $replace[ "[$column]" ] = $r->{$column};
  273. }
  274. else {
  275. $replace[ "[$column]" ] = "";
  276. }
  277. }
  278. // Set the value.
  279. $values[$r->id] = strtr($options['label_string'], $replace);
  280. }
  281. return $values;
  282. }
  283. /**
  284. * Describes this field to Views.
  285. * @see TripalField::viewsData().
  286. */
  287. public function viewsData($view_base_id) {
  288. $data = parent::viewsData($view_base_id);
  289. $field_name = $this->field['field_name'];
  290. $elements = $this->elementInfo();
  291. $field_details = $elements[$field_term];
  292. // Get any titles or help text that is overriden.
  293. $title = ucfirst($this->instance['label']);
  294. if (array_key_exists('label', $field_details)) {
  295. $title = $field_details['label'];
  296. }
  297. $help = $this->instance['description'];
  298. if (array_key_exists('help', $field_details)) {
  299. $help = $field_details['help'];
  300. }
  301. // Add another entry to views for this field providing an alternate
  302. // filter handler. This way, the views integration is backwards compatible
  303. // and users simply select the "Allowed Values" version of their field
  304. // to expose it as a select list.
  305. $data[$view_base_id][$field_name . '_values'] = array(
  306. 'title' => $title . ' (Allowed Values)',
  307. 'help' => $help,
  308. 'filter' => array(
  309. 'handler' => 'tripal_views_handler_filter_string',
  310. ),
  311. );
  312. return $data;
  313. }
  314. /**
  315. * @see TripalField::instanceSettingsForm()
  316. */
  317. public function instanceSettingsForm() {
  318. // Make sure we don't lose our Chado table mappings when the settings
  319. // are updated. Setting them as values in the form ensures they don't
  320. // get accidentally overwritten.
  321. $element['base_table'] = array(
  322. '#type' => 'value',
  323. '#value' => $this->instance['settings']['base_table'],
  324. );
  325. $element['chado_table'] = array(
  326. '#type' => 'value',
  327. '#value' => $this->instance['settings']['chado_table'],
  328. );
  329. $element['chado_column'] = array(
  330. '#type' => 'value',
  331. '#value' => $this->instance['settings']['chado_column'],
  332. );
  333. return $element;
  334. }
  335. }