tripal_chado.field_storage.inc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. <?php
  2. /**
  3. * Implements hook_field_storage_info().
  4. */
  5. function tripal_chado_field_storage_info() {
  6. return array(
  7. 'field_chado_storage' => array(
  8. 'label' => t('Chado'),
  9. 'description' => t('Stores fields in the local Chado database.'),
  10. 'settings' => array(),
  11. // The logo_url key is supported by Tripal. It's not a Drupal key. It's
  12. // used for adding a logo or picture for the data store to help make it
  13. // more easily recognized on the field_ui_field_overview_form. Ideally
  14. // the URL should point to a relative path on the local Drupal site.
  15. 'logo_url' => url(drupal_get_path('module', 'tripal') . '/theme/images/250px-ChadoLogo.png'),
  16. ),
  17. );
  18. }
  19. /**
  20. * Implements hook_field_storage_write().
  21. */
  22. function tripal_chado_field_storage_write($entity_type, $entity, $op, $fields) {
  23. // Get the bundle and the term for this entity.
  24. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  25. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  26. $term = reset($term);
  27. // Convert the Tripal term entity into the appropriate record in Chado.
  28. $dbxref = tripal_get_dbxref(array('accession' => $term->accession, 'db_id' => array('name' => $term->vocab->vocabulary)));
  29. $cvterm = tripal_get_cvterm(array('dbxref_id' => $dbxref->dbxref_id));
  30. // Get the base table, type field and record_id from the entity.
  31. $base_table = $entity->chado_table;
  32. $type_field = $entity->chado_column;
  33. $record = $entity->chado_record;
  34. $record_id = $entity->chado_record_id;
  35. $base_schema = chado_get_schema($base_table);
  36. $base_pkey = $base_schema['primary key'][0];
  37. // Convert the fields into a key/value list of fields and their values.
  38. $field_vals = tripal_chado_field_storage_write_merge_fields($fields, $entity_type, $entity);
  39. // First, write the record for the base table. If we have a record id then
  40. // this is an update and we need to set the primary key. If not, then this
  41. // is an insert and we need to set the type_id if the table supports it.
  42. $values = $field_vals[$base_table];
  43. if ($record_id) {
  44. $values[$base_pkey] = $record_id;
  45. }
  46. elseif ($type_field) {
  47. $values[$type_field] = $cvterm->cvterm_id;
  48. }
  49. $base_record_id = tripal_chado_field_storage_write_table($base_table, $values);
  50. // If this is an insert then add the chado_entity record.
  51. if ($op == FIELD_STORAGE_INSERT) {
  52. // Add a record to the chado_entity table so that the data for the
  53. // fields can be pulled from Chado when loaded the next time.
  54. $record = array(
  55. 'entity_id' => $entity->id,
  56. 'record_id' => $base_record_id,
  57. 'data_table' => $base_table,
  58. );
  59. $success = drupal_write_record('chado_entity', $record);
  60. if (!$success) {
  61. drupal_set_message('Unable to insert new Chado entity.', 'error');
  62. }
  63. }
  64. // Now that we have handled the base table, we need to handle linking tables.
  65. foreach ($field_vals as $table_name => $details) {
  66. // Skip the base table as we've already dealt with it.
  67. if ($table_name == $base_table) {
  68. continue;
  69. }
  70. foreach ($details as $delta => $values) {
  71. $record_id = tripal_chado_field_storage_write_table($table_name, $values);
  72. }
  73. }
  74. }
  75. /**
  76. * Write (inserts/updates/deletes) values for a Chado table.
  77. *
  78. * The $values array is of the same format used by chado_insert_record() and
  79. * chado_update_record(). However, both of those methods will use any nested
  80. * arrays (i.e. representing foreign keys) to select an appropriate record ID
  81. * that can be substituted as the value. Here, the nested arrays are
  82. * either inserted or updated as well, but the choice is determined if the
  83. * primary key value is present. If present an update occurs, if not present
  84. * then an insert occurs.
  85. *
  86. * This function is recursive and nested arrays from the lowest point of the
  87. * "tree" are dealt with first.
  88. *
  89. * @param $table_name
  90. * The name of the table on which the insertion/update is performed.
  91. * @param $values
  92. * The values array for the insertion.
  93. *
  94. * @throws Exception
  95. *
  96. * @return
  97. * The unique record ID.
  98. */
  99. function tripal_chado_field_storage_write_table($table_name, $values) {
  100. $schema = chado_get_schema($table_name);
  101. $fkeys = $schema['foreign keys'];
  102. $pkey = $schema['primary key'][0];
  103. // Fields with a cardinality greater than 1 will often submit an
  104. // empty form. We want to remove these empty submissions. We can detect
  105. // them if all of the fields are empty.
  106. $num_empty = 0;
  107. foreach ($values as $column => $value) {
  108. if (!$value) {
  109. $num_empty++;
  110. }
  111. }
  112. if ($num_empty == count(array_keys($values))) {
  113. return '';
  114. }
  115. // If the primary key column has a value but all other values are empty then
  116. // this is a delete.
  117. if (array_key_exists($pkey, $values) and $values[$pkey]) {
  118. $num_vals = 0;
  119. foreach ($values as $value) {
  120. if ($value) {
  121. $num_vals++;
  122. }
  123. }
  124. if ($num_vals == 1) {
  125. $new_vals[$pkey] = $values[$pkey];
  126. if (!chado_delete_record($table_name, $new_vals)) {
  127. throw new Exception('Could not delete record from table: "' . $table_name . '".');
  128. }
  129. return '';
  130. }
  131. }
  132. // If the primary key column does not have a value then this is an insert.
  133. if (!array_key_exists($pkey, $values) or !$values[$pkey] or !isset($values[$pkey])) {
  134. // Before inserting, we want to make sure the record does not
  135. // already exist. Using the unique constraint check for a matching record.
  136. $options = array('is_duplicate' => TRUE);
  137. $is_duplicate = chado_select_record($table_name, array('*'), $values, $options);
  138. if($is_duplicate) {
  139. $record = chado_select_record($table_name, array('*'), $values);
  140. return $record[0]->$pkey;
  141. }
  142. // Insert the values array as a new record in the table but remove the
  143. // pkey as it should be set.
  144. $new_vals = $values;
  145. unset($new_vals[$pkey]);
  146. $record = chado_insert_record($table_name, $new_vals);
  147. if ($record === FALSE) {
  148. throw new Exception('Could not insert Chado record into table: "' . $table_name . '".');
  149. }
  150. return $record[$pkey];
  151. }
  152. // If we've made it to this point then this is an update.
  153. // TODO: what if the unique constraint matches another record? That is
  154. // not being tested for here.
  155. $match[$pkey] = $values[$pkey];
  156. if (!chado_update_record($table_name, $match, $values)) {
  157. drupal_set_message("Could not update Chado record in table: $table_name.", 'error');
  158. }
  159. return $values[$pkey];
  160. }
  161. /**
  162. * Implements hook_field_storage_load().
  163. *
  164. * Responsible for loading the fields from the Chado database and adding
  165. * their values to the entity.
  166. */
  167. function tripal_chado_field_storage_load($entity_type, $entities, $age,
  168. $fields, $options) {
  169. $load_current = $age == FIELD_LOAD_CURRENT;
  170. global $language;
  171. $langcode = $language->language;
  172. foreach ($entities as $id => $entity) {
  173. if (property_exists($entity, 'chado_table')) {
  174. // Get the base table and record id for the fields of this entity.
  175. $base_table = $entity->chado_table;
  176. $type_field = $entity->chado_column;
  177. $record_id = $entity->chado_record_id;
  178. }
  179. else {
  180. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  181. $base_table = $bundle->data_table;
  182. $type_field = $bundle->type_column;
  183. // Get the base table and record id for the fields of this entity.
  184. $details = db_select('chado_entity', 'ce')
  185. ->fields('ce')
  186. ->condition('entity_id', $entity->id)
  187. ->execute()
  188. ->fetchObject();
  189. if (!$details) {
  190. // TODO: what to do if record is missing!
  191. }
  192. $record_id = isset($details->record_id) ? $details->record_id : '';
  193. }
  194. // Get this table's schema.
  195. $schema = chado_get_schema($base_table);
  196. $pkey_field = $schema['primary key'][0];
  197. // Get the base record if one exists
  198. $columns = array('*');
  199. $match = array($pkey_field => $record_id);
  200. $record = chado_generate_var($base_table, $match);
  201. $entity->chado_record = $record;
  202. // Iterate through the entity's fields so we can get the column names
  203. // that need to be selected from each of the tables represented.
  204. $tables = array();
  205. foreach ($fields as $field_id => $ids) {
  206. // By the time this hook runs, the relevant field definitions have been
  207. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  208. // on each field individually is more efficient than loading all fields in
  209. // memory upfront with field_info_field_by_ids().
  210. $field = field_info_field_by_id($field_id);
  211. $field_name = $field['field_name'];
  212. $field_type = $field['type'];
  213. $field_module = $field['module'];
  214. // Get the instnace for this field
  215. $instance = field_info_instance($entity_type, $field_name, $entity->bundle);
  216. // Skip fields that don't map to a Chado table (e.g. kvproperty_adder).
  217. if (!array_key_exists('settings', $instance) or !array_key_exists('chado_table', $instance['settings'])) {
  218. continue;
  219. }
  220. // Get the Chado table and column for this field.
  221. $field_table = $instance['settings']['chado_table'];
  222. $field_column = $instance['settings']['chado_column'];
  223. // There are only two types of fields: 1) fields that represent a single
  224. // column of the base table, or 2) fields that represent a linked record
  225. // in a many-to-one relationship with the base table.
  226. // Type 1: fields from base tables.
  227. if ($field_table == $base_table) {
  228. // Set an empty value by default, and if there is a record, then update.
  229. $entity->{$field_name}['und'][0]['value'] = '';
  230. if ($record and property_exists($record, $field_column)) {
  231. // If the field column is an object then it's a FK to another table.
  232. // and because $record object is created by the chado_generate_var()
  233. // function we must go one more level deeper to get the value
  234. if (is_object($record->$field_column)) {
  235. $fkey_column = $field_column;
  236. foreach($schema['foreign keys'] as $table => $fk_details) {
  237. foreach($fk_details['columns'] as $lfkey => $rfkey) {
  238. if ($lfkey == $field_column) {
  239. $fkey_column = $rfkey;
  240. }
  241. }
  242. }
  243. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__' . $field_column] = $record->$field_column->$fkey_column;
  244. }
  245. else {
  246. // For non FK fields we'll make the field value be the same
  247. // as the column value.
  248. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  249. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__' . $field_column] = $record->$field_column;
  250. }
  251. }
  252. // Allow the creating module to alter the value if desired. The
  253. // module should do this if the field has any other form elements
  254. // that need populationg besides the value which was set above.
  255. tripal_load_include_field_class($field_type);
  256. if (class_exists($field_type) and is_subclass_of($field_type, 'TripalField')) {
  257. $tfield = new $field_type($field, $instance);
  258. $tfield->load($entity, array('record' => $record));
  259. }
  260. // For text fields that were not handled by a TripalField class we
  261. // want to automatically expand those fields.
  262. else {
  263. if ($schema['fields'][$field_column]['type'] == 'text') {
  264. $record = chado_expand_var($record, 'field', "$field_table.$field_column");
  265. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  266. // Text fields that have a text_processing == 1 setting need a
  267. // special 'format' element too:
  268. if (array(key_exists('text_processing', $instance['settings']) and
  269. $instance['settings']['text_processing'] == 1)) {
  270. // TODO: we need a way to write the format back to the
  271. // instance settings if the user changes it when using the form.
  272. $entity->{$field_name}['und'][0]['format'] = array_key_exists('format', $instance['settings']) ? $instance['settings']['format'] : 'full_html';
  273. }
  274. }
  275. }
  276. }
  277. // Type 2: fields for linked records. These fields will have any number
  278. // of form elements that might need populating so we'll offload the
  279. // loading of these fields to the field itself.
  280. if ($field_table != $base_table) {
  281. // Set an empty value by default, and let the hook function update it.
  282. $entity->{$field_name}['und'][0]['value'] = '';
  283. tripal_load_include_field_class($field_type);
  284. if (class_exists($field_type) && method_exists($field_type, 'load')) {
  285. $tfield = new $field_type($field, $instance);
  286. $tfield->load($entity, array('record' => $record));
  287. }
  288. }
  289. } // end: foreach ($fields as $field_id => $ids) {
  290. } // end: foreach ($entities as $id => $entity) {
  291. }
  292. /**
  293. * Merges the values of all fields into a single array keyed by table name.
  294. */
  295. function tripal_chado_field_storage_write_merge_fields($fields, $entity_type, $entity) {
  296. $all_fields = array();
  297. $base_fields = array();
  298. // Iterate through all of the fields and organize them into a
  299. // new fields array keyed by the table name
  300. foreach ($fields as $field_id => $ids) {
  301. // Get the field name and information about it.
  302. $field = field_info_field_by_id($field_id);
  303. $field_name = $field['field_name'];
  304. $instance = field_info_instance('TripalEntity', $field['field_name'], $entity->bundle);
  305. // Some fields (e.g. chado_linker_cvterm_adder) don't add data to
  306. // Chado so they don't have a table, but they are still attached to the
  307. // entity. Just skip these.
  308. if (!array_key_exists('chado_table', $instance['settings'])) {
  309. continue;
  310. }
  311. $chado_table = $instance['settings']['chado_table'];
  312. $chado_column = $instance['settings']['chado_column'];
  313. $base_table = $instance['settings']['base_table'];
  314. // Iterate through the field's items. Fields with cardinality ($delta) > 1
  315. // are multi-valued.
  316. $items = field_get_items($entity_type, $entity, $field_name);
  317. $temp = array();
  318. foreach ($items as $delta => $item) {
  319. // A field may have multiple items. The field can use items
  320. // indexed with "chado-" to represent values that should map directly
  321. // to chado tables and fields.
  322. foreach ($item as $item_name => $value) {
  323. $matches = array();
  324. if (preg_match('/^chado-(.*?)__(.*?)$/', $item_name, $matches)) {
  325. $table_name = $matches[1];
  326. $column_name = $matches[2];
  327. // If this field belongs to the base table then we just add
  328. // those values in... there's no delta.
  329. if ($table_name == $base_table) {
  330. $base_fields[$table_name][$column_name] = $value;
  331. }
  332. else {
  333. $temp[$table_name][$delta][$column_name] = $value;
  334. }
  335. }
  336. }
  337. // If there is no value set for the field using the
  338. // chado-[table_name]__[field name] naming schema then check if a 'value'
  339. // item is present and if so use that for the table column value.
  340. if ((!array_key_exists($chado_table, $temp) or
  341. !array_key_exists($delta, $temp[$chado_table]) or
  342. !array_key_exists($chado_column, $temp[$chado_table][$delta])) and
  343. array_key_exists('value', $items[$delta]) and
  344. !is_array($items[$delta]['value'])) {
  345. // If this field belongs to the base table then we just add
  346. // those values in... there's no delta.
  347. if ($base_table == $chado_table) {
  348. $base_fields[$chado_table][$chado_column] = $item['value'];
  349. }
  350. else {
  351. $temp[$chado_table][$delta][$chado_column] = $item['value'];
  352. }
  353. }
  354. }
  355. // Now merge the records for this field with the $new_fields array
  356. foreach ($temp as $table_name => $details) {
  357. foreach ($details as $delta => $list) {
  358. $all_fields[$table_name][] = $list;
  359. }
  360. }
  361. }
  362. $all_fields = array_merge($base_fields, $all_fields);
  363. return $all_fields;
  364. }
  365. /**
  366. * Implements hook_field_storage_query().
  367. */
  368. function tripal_chado_field_storage_query($query) {
  369. // Initialize the result array.
  370. $result = array(
  371. 'TripalEntity' => array()
  372. );
  373. // There must always be an entity filter that includes the bundle. Otherwise
  374. // it would be too overwhelming to search every table of every content type
  375. // for a matching field.
  376. if (!array_key_exists('bundle', $query->entityConditions)) {
  377. return $result;
  378. }
  379. $bundle = tripal_load_bundle_entity(array('name' => $query->entityConditions['bundle']));
  380. $data_table = $bundle->data_table;
  381. $type_column = $bundle->type_column;
  382. $type_id = $bundle->type_id;
  383. $schema = chado_get_schema($data_table);
  384. $pkey = $schema['primary key'][0];
  385. // Initialize the Query object.
  386. $cquery = chado_db_select($data_table, 'base');
  387. $cquery->fields('base', array($pkey));
  388. // Iterate through all the conditions and add to the filters array
  389. // a chado_select_record compatible set of filters.
  390. foreach ($query->fieldConditions as $index => $condition) {
  391. $field = $condition['field'];
  392. $field_name = $field['field_name'];
  393. $field_type = $field['type'];
  394. // Skip conditions that don't belong to this storage type.
  395. if ($field['storage']['type'] != 'field_chado_storage') {
  396. continue;
  397. }
  398. // The Chado settings for a field are part of the instance and each bundle
  399. // can have the same field but with different Chado mappings. Therefore,
  400. // we need to iterate through the bundles to get the field instances.
  401. foreach ($field['bundles']['TripalEntity'] as $bundle_name) {
  402. // If there is a bundle filter for the entity and if the field is not
  403. // associated with the bundle then skip it.
  404. if (array_key_exists('bundle', $query->entityConditions)) {
  405. if (strtolower($query->entityConditions['bundle']['operator']) == 'in' and
  406. !array_key_exists($bundle_name, $query->entityConditions['bundle']['value'])) {
  407. continue;
  408. }
  409. else if ($query->entityConditions['bundle']['value'] != $bundle_name) {
  410. continue;
  411. }
  412. }
  413. // Allow the field to update the query object.
  414. $instance = field_info_instance('TripalEntity', $field['field_name'], $bundle_name);
  415. if (tripal_load_include_field_class($field_type)) {
  416. $field_obj = new $field_type($field, $instance);
  417. $field_obj->query($cquery, $condition);
  418. }
  419. }
  420. } // end foreach ($query->fieldConditions as $index => $condition) {
  421. // Now get the list for sorting.
  422. foreach ($query->order as $index => $sort) {
  423. // We only handle ordering by field type here.
  424. if ($sort['type'] != 'field') {
  425. continue;
  426. }
  427. $field = $sort['specifier']['field'];
  428. $field_type = $field['type'];
  429. $field_name = $field['field_name'];
  430. // Skip sorts that don't belong to this storage type.
  431. if ($field['storage']['type'] != 'field_chado_storage') {
  432. continue;
  433. }
  434. $column = $sort['specifier']['column'];
  435. $direction = $sort['direction'];
  436. // See if there is a ChadoField class for this instance. If not then do
  437. // our best to order the field.
  438. $instance = field_info_instance('TripalEntity', $field_name, $bundle_name);
  439. if (tripal_load_include_field_class($field_type)) {
  440. $field_obj = new $field_type($field, $instance);
  441. $field_obj->queryOrder($cquery, array('column' => $column, 'direction' => $direction));
  442. }
  443. // There is no class so do our best to order the data by this field
  444. else {
  445. $base_table = $instance['settings']['base_table'];
  446. $chado_table = $instance['settings']['chado_table'];
  447. $table_column = tripal_get_chado_semweb_column($chado_table, $column);
  448. if ($table_column) {
  449. if ($chado_table == $base_table) {
  450. $cquery->orderBy('base.' . $table_column, $direction);
  451. }
  452. else {
  453. // TODO: how do we handle a field that doesn't map to the base table.
  454. // We would expect that all of these would be custom field and
  455. // the ChadoField::queryOrder() function would be implemented.
  456. }
  457. }
  458. else {
  459. // TODO: handle when the name can't be matched to a table column.
  460. }
  461. }
  462. }
  463. // Now join with the chado_entity table to get published records only.
  464. $cquery->join('chado_entity', 'CE', "CE.record_id = base.$pkey");
  465. $cquery->join('tripal_entity', 'TE', "CE.entity_id = TE.id");
  466. $cquery->fields('CE', array('entity_id'));
  467. $cquery->condition('CE.data_table', $data_table);
  468. if (array_key_exists('start', $query->range)) {
  469. $cquery->range($query->range['start'], $query->range['length']);
  470. }
  471. $records = $cquery->execute();
  472. $result = array();
  473. while ($record = $records->fetchObject()) {
  474. $ids = array($record->entity_id, 0, $bundle_name);
  475. $result['TripalEntity'][$record->entity_id] = entity_create_stub_entity('TripalEntity', $ids);
  476. }
  477. return $result;
  478. }
  479. /**
  480. * @return
  481. * An array containing the chado_select_record() compatible array.
  482. */
  483. function tripal_chado_field_storage_query_build_sql(&$sql, $prev_table, $prev_column, $prev_term, $chado_table, $query_terms, $condition, $value, $depth = 0) {
  484. // Get schema information for the previous (linker) Chado table.
  485. $pschema = chado_get_schema($prev_table);
  486. $ppkey = $pschema['primary key'][0];
  487. $pfkeys = $pschema['foreign keys'];
  488. // Get schema information for the current Chado table.
  489. $schema = chado_get_schema($chado_table);
  490. $pkey = $schema['primary key'][0];
  491. $fkeys = $schema['foreign keys'];
  492. // Get the first query term from the list and find out what column this
  493. // term maps to in the Chado table.
  494. $term = array_shift($query_terms);
  495. $chado_column = tripal_get_chado_semweb_column($chado_table, $term);
  496. if (!$chado_column) {
  497. // TODO: we could get to this point because a field has a value that
  498. // doesn't map to a database column but is a manually created
  499. // element. How do we deal with those?
  500. return FALSE;
  501. }
  502. // reformat that term so it's compatible with SQL
  503. $term = preg_replace('/[^\w]/', '_', $term);
  504. // A query can be an array of column names separated by a period. We
  505. // want to split them apart and just deal with the column at the head
  506. // of the array. But before dealing with that head, we will recurse so that
  507. // we build our filters array from the bottom up.
  508. if (count($query_terms) > 0) {
  509. // Since the $query_terms is not a single element that implies this
  510. // query term represents a foreign key.
  511. // We don't know which direction the foreign key is going, so we'll have
  512. // to check both the previous and current tables to build the join
  513. // statement correctly.
  514. if (array_key_exists($prev_table, $fkeys) and
  515. array_key_exists($chado_column, $fkeys[$prev_table]['columns'])) {
  516. $fkey = $fkeys[$prev_table]['columns'][$chado_column];
  517. $sql['join'][] = 'INNER JOIN {' . $chado_table . '} ' . $term . ' ON ' . $prev_term . '.' . $fkey . ' = ' . $term . '.' . $chado_column;
  518. }
  519. else {
  520. $sql['join'][] = 'INNER JOIN {' . $chado_table . '} ' . $term . ' ON ' . $prev_term . '.' . $prev_column . ' = ' . $term . '.' . $chado_column;
  521. }
  522. // Get the table that this foreign key links to.
  523. $next_table = '';
  524. foreach ($fkeys as $fktable_name => $fk_details) {
  525. foreach ($fk_details['columns'] as $lfkey => $rfkey) {
  526. if ($lfkey == $chado_column) {
  527. $next_table = $fktable_name;
  528. }
  529. }
  530. }
  531. if ($next_table) {
  532. tripal_chado_field_storage_query_build_sql($sql, $chado_table, $chado_column, $term, $next_table, $query_terms, $condition, $value, $depth++);
  533. }
  534. else {
  535. // TODO: we could get to this point because a field has a value that
  536. // doesn't map to a database column but is a manually created
  537. // element. How do we deal with those?
  538. return FALSE;
  539. }
  540. return FALSE;
  541. }
  542. // We don't know which direction the foreign key is going, so we'll have
  543. // to check both the previous and current tables to build the join
  544. // statement correctly.
  545. if (array_key_exists($prev_table, $fkeys) and
  546. array_key_exists($chado_column, $fkeys[$prev_table]['columns'])) {
  547. $fkey = $fkeys[$prev_table]['columns'][$chado_column];
  548. $sql['join'][] = 'INNER JOIN {' . $chado_table . '} ' . $term . ' ON ' . $prev_term . '.' . $fkey . ' = ' . $term . '.' . $chado_column;
  549. }
  550. else {
  551. $sql['join'][] = 'INNER JOIN {' . $chado_table . '} ' . $term . ' ON ' . $prev_term . '.' . $prev_column . ' = ' . $term . '.' . $chado_column;
  552. }
  553. // Use the appropriate operator.
  554. $operator = $condition['operator'] ? $condition['operator'] : '=';
  555. switch ($operator) {
  556. case '=':
  557. $sql['where'][] = "$term.$chado_column = :value";
  558. $sql['args'][':value'] = $value;
  559. break;
  560. case '>':
  561. case '>=':
  562. case '<':
  563. case '<=':
  564. $sql['where'][] = "$term.$chado_column $op :value";
  565. $sql['args'][':value'] = $value;
  566. break;
  567. case '<>':
  568. $sql['where'][] = "$term.$chado_column $op :value";
  569. $sql['args'][':value'] = $value;
  570. break;
  571. case 'CONTAINS':
  572. $sql['where'][] = "$term.$chado_column LIKE :value";
  573. $sql['args'][':value'] = '%' . $value . '%';
  574. break;
  575. case 'NOT':
  576. $subfilters[$chado_column] = array(
  577. 'op' => 'NOT LIKE',
  578. 'data' => '%' . $value . '%',
  579. );
  580. $sql['where'][] = "$term.$chado_column NOT LIKE :value";
  581. $sql['args'][':value'] = '%' . $value . '%';
  582. break;
  583. case 'STARTS WITH':
  584. $sql['where'][] = "$term.$chado_column LIKE :value";
  585. $sql['args'][':value'] = $value . '%';
  586. break;
  587. case 'NOT STARTS':
  588. $sql['where'][] = "$term.$chado_column NOT LIKE :value";
  589. $sql['args'][':value'] = $value . '%';
  590. break;
  591. case 'ENDS WITH':
  592. $sql['where'][] = "$term.$chado_column LIKE :value";
  593. $sql['args'][':value'] = '%' . $value;
  594. break;
  595. case 'NOT ENDS':
  596. $sql['where'][] = "$term.$chado_column NOT LIKE :value";
  597. $sql['args'][':value'] = '%' . $value;
  598. break;
  599. default:
  600. // unrecognized operation.
  601. break;
  602. }
  603. }