ChadoField.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. class ChadoField extends TripalField {
  3. // The default label 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 = [
  13. 'storage' => 'field_chado_storage',
  14. ];
  15. // Provide a list of instance specific settings. These can be accessed within
  16. // the instanceSettingsForm. When the instanceSettingsForm is submitted
  17. // then Drupal will automatically change these settings for the instance.
  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 = [
  23. // The short name for the vocabulary (e.g. schema, 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 = [
  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
  137. * field instance.
  138. *
  139. * @param $keyword
  140. * A string option used to filter the distinct list. This is used when
  141. * creating an autocomplete. For all distinct values, set this to NULL.
  142. * @param $options
  143. * An array where options for how to generate this list can be specified.
  144. * Supported options include:
  145. * - limit: how many results to limit to (Default: 25)
  146. * - label_string: a string with tokens that should be used to generate
  147. * the human-readable values in the returned list.
  148. *
  149. * The following example shows you how to pull all the value list for a
  150. * specific instance of a field.
  151. *
  152. * @code
  153. * // In this example we want the values for the obi__organism field
  154. * // attached to the Tripal Content Type with a machine name of bio_data_17:
  155. * $field_name = 'obi__organism';
  156. * $bundle_name = 'bio_data_17';
  157. *
  158. * // The following two calls get information about the field we want the
  159. * values for.
  160. * $field_info = field_info_field($field_name);
  161. * $instance_info = field_info_instance('TripalEntity', $field_name,
  162. * $bundle_name);
  163. * // Construct the Field instance we want the values for.
  164. * $instance = new ChadoField($field_info, $instance_info);
  165. *
  166. * // Retrieve the values.
  167. * // $values will be an array containing the distinct set of values for this
  168. * field instance.
  169. * $values = $instance->getValueList();
  170. * @endcode
  171. *
  172. * @return
  173. * An array of values.
  174. */
  175. public function getValueList($options = [], $keyword = NULL) {
  176. $values = [];
  177. // Set some defaults.
  178. $options['limit'] = (isset($options['limit'])) ? $options['limit'] : 25;
  179. $options['label_string'] = (isset($options['label_string'])) ? $options['label_string'] : '';
  180. // Make sure we know the chado table and column.
  181. // If not, we can't give them a list *shrugs*.
  182. if (!isset($this->instance['settings']['chado_table']) OR !isset($this->instance['settings']['chado_column'])) {
  183. tripal_report_error(
  184. 'TripalField',
  185. TRIPAL_WARNING,
  186. 'Values List: Unable to generate a values list for %field_name since we don\'t know it\'s chado table/column.',
  187. ['%field_name' => $this->instance['field_name']]
  188. );
  189. return FALSE;
  190. }
  191. // First get some important info about the chado table.column this field is attached to.
  192. $chado_table = $this->instance['settings']['chado_table'];
  193. $chado_column = $this->instance['settings']['chado_column'];
  194. $base_table = $this->instance['settings']['base_table'];
  195. $bschema = chado_get_schema($base_table);
  196. // Now build the distinct query.
  197. if ($chado_table == $base_table) {
  198. // Is the current column a foreign key to another table?
  199. $is_fk = FALSE;
  200. $fk_table = $fk_column = NULL;
  201. foreach ($bschema['foreign keys'] as $k => $v) {
  202. if (isset($v['columns'][$chado_column])) {
  203. $is_fk = TRUE;
  204. $fk_table = $v['table'];
  205. $fk_column = $v['columns'][$chado_column];
  206. }
  207. }
  208. // Check if this column is a foreign key to another one.
  209. // If so we would like to travel through the relationship
  210. // to capture a better human-readable option.
  211. if ($is_fk) {
  212. // Determine the query.
  213. $sql = "SELECT base.$chado_column as id, fk.*
  214. FROM {" . $chado_table . "} base
  215. LEFT JOIN {" . $fk_table . "} fk ON base.$chado_column=fk.$fk_column
  216. GROUP BY base.$chado_column, fk.$fk_column
  217. LIMIT " . $options['limit'];
  218. // Choose a default label string, if needed.
  219. if (empty($options['label_string'])) {
  220. $fkschema = chado_get_schema($fk_table);
  221. if (isset($fkschema['fields']['name'])) {
  222. $options['label_string'] = '[name]';
  223. }
  224. elseif (isset($fkschema['fields']['uniquename'])) {
  225. $options['label_string'] = '[uniquename]';
  226. }
  227. elseif (isset($fkschema['fields']['accession'])) {
  228. $options['label_string'] = '[accession]';
  229. }
  230. elseif (isset($fkschema['fields']['title'])) {
  231. $options['label_string'] = '[title]';
  232. }
  233. elseif ($fk_table == 'organism') {
  234. $options['label_string'] = '[genus] [species]';
  235. }
  236. else {
  237. tripal_report_error(
  238. 'TripalField',
  239. TRIPAL_WARNING,
  240. '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].',
  241. ['%field_name' => $this->instance['field_name']]
  242. );
  243. return FALSE;
  244. }
  245. }
  246. }
  247. // Not a foreign key, so just make the key and value from the base table.
  248. else {
  249. $sql = "SELECT $chado_column as id, $chado_column
  250. FROM {" . $chado_table . "} base
  251. GROUP BY $chado_column
  252. LIMIT " . $options['limit'];
  253. // Choose a default label string, if needed.
  254. if (empty($options['label_string'])) {
  255. $options['label_string'] = '[' . $chado_column . ']';
  256. }
  257. }
  258. }
  259. else {
  260. tripal_report_error(
  261. 'TripalField',
  262. TRIPAL_WARNING,
  263. 'Unable to retrieve a values list for %field_name since it is not a direct column in %base',
  264. ['%field_name' => $this->instance['field_name'], '%base' => $base_table]
  265. );
  266. return FALSE;
  267. }
  268. $results = chado_query($sql);
  269. // Pre-process the label string for better performance.
  270. // Each token is enclosed in square brackets and should be the name of a chado column.
  271. preg_match_all('/\[(\w+)\]/', $options['label_string'], $matches);
  272. $tokens = $matches[1];
  273. foreach ($results as $r) {
  274. // Determine the label using the label_string option.
  275. $label = $options['label_string'];
  276. $replace = [];
  277. foreach ($tokens as $column) {
  278. if (isset($r->{$column})) {
  279. $replace["[$column]"] = $r->{$column};
  280. }
  281. else {
  282. $replace["[$column]"] = "";
  283. }
  284. }
  285. // Set the value.
  286. $values[$r->id] = strtr($options['label_string'], $replace);
  287. }
  288. return $values;
  289. }
  290. /**
  291. * @see TripalField::instanceSettingsForm()
  292. */
  293. public function instanceSettingsForm() {
  294. $element = parent::instanceSettingsForm();
  295. // Make sure we don't lose our Chado table mappings when the settings
  296. // are updated. Setting them as values in the form ensures they don't
  297. // get accidentally overwritten.
  298. $element['base_table'] = [
  299. '#type' => 'value',
  300. '#value' => $this->instance['settings']['base_table'],
  301. ];
  302. $element['chado_table'] = [
  303. '#type' => 'value',
  304. '#value' => $this->instance['settings']['chado_table'],
  305. ];
  306. $element['chado_column'] = [
  307. '#type' => 'value',
  308. '#value' => $this->instance['settings']['chado_column'],
  309. ];
  310. return $element;
  311. }
  312. }