tripal_chado.field_storage.inc 27 KB

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