tripal_chado.field_storage.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. $cvterm = $term->details['cvterm'];
  28. // Get the base table, type field and record_id from the entity.
  29. $base_table = $entity->chado_table;
  30. $type_field = $entity->chado_column;
  31. $record = $entity->chado_record;
  32. $record_id = $entity->chado_record_id;
  33. $base_schema = chado_get_schema($base_table);
  34. $base_pkey = $base_schema['primary key'][0];
  35. // Convert the fields into a key/value list of fields and their values.
  36. $field_vals = tripal_chado_field_storage_write_merge_fields($fields, $entity_type, $entity);
  37. //dpm($field_vals);
  38. // First, write the record for the base table. If we have a record id then
  39. // this is an upate and we need to set the primary key. If not, then this
  40. // is an insert and we need to set the type_id if the table supports it.
  41. $values = $field_vals[$base_table][0];
  42. if ($record_id) {
  43. $values[$base_pkey] = $record_id;
  44. }
  45. elseif ($type_field) {
  46. $values[$type_field] = $cvterm->cvterm_id;
  47. }
  48. $base_record_id = tripal_chado_field_storage_write_table($base_table, $values);
  49. // If this is an insert then add the chado_entity record.
  50. if ($op == FIELD_STORAGE_INSERT) {
  51. // Add a record to the chado_entity table so that the data for the
  52. // fields can be pulled from Chado when loaded the next time.
  53. $record = array(
  54. 'entity_id' => $entity->id,
  55. 'record_id' => $base_record_id,
  56. 'data_table' => $base_table,
  57. 'type_table' => $base_table,
  58. 'field' => $type_field,
  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/oupdates) a nested array of values for a 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. * @throws Exception
  95. * @return
  96. * The unique record ID.
  97. */
  98. function tripal_chado_field_storage_write_table($table_name, $values) {
  99. $schema = chado_get_schema($table_name);
  100. $fkeys = $schema['foreign keys'];
  101. $pkey = $schema['primary key'][0];
  102. // Before inserting or updating this table, recurse if there are any
  103. // nested FK array values.
  104. foreach ($values as $column => $value) {
  105. // If this value is an array then it must be a FK... let's recurse.
  106. if (is_array($value)) {
  107. // Find the name of the FK table for this column.
  108. $fktable_name = '';
  109. foreach ($fkeys as $fktable => $details) {
  110. foreach ($details['columns'] as $fkey_lcolumn => $fkey_rcolumn) {
  111. if ($fkey_lcolumn == $column) {
  112. $fktable_name = $fktable;
  113. }
  114. }
  115. }
  116. // Recurse on this recod.
  117. $record_id = tripal_chado_field_storage_write_table($fktable_name, $values[$column]);
  118. $values[$column] = $record_id;
  119. }
  120. }
  121. // Fields with a cardinality greater than 1 will often submit an
  122. // empty form. We want to remove these empty submissions. We can detect
  123. // them if all of the fields are empty.
  124. $num_empty = 0;
  125. foreach ($values as $column => $value) {
  126. if (!$value) {
  127. $num_empty++;
  128. }
  129. }
  130. if ($num_empty == count(array_keys($values))) {
  131. return '';
  132. }
  133. // If the primary key column has a value then this will be an udpate,
  134. // otherwise it's an insert.
  135. if (!array_key_exists($pkey, $values) or !$values[$pkey]) {
  136. // Before inserting, we want to make sure the record does not
  137. // already exist. Using the unique constraint check for a matching record.
  138. $options = array('is_duplicate' => TRUE);
  139. $is_duplicate = chado_select_record($table_name, array('*'), $values, $options);
  140. if($is_duplicate) {
  141. $record = chado_select_record($table_name, array('*'), $values);
  142. return $record[0]->$pkey;
  143. }
  144. // Insert the values array as a new record in the table.
  145. $record = chado_insert_record($table_name, $values);
  146. if ($record === FALSE) {
  147. throw new Exception('Could not insert Chado record into table: "' . $table_name . '".');
  148. }
  149. return $record[$pkey];
  150. }
  151. // We have an incoming record_id so this is an update.
  152. else {
  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. /**
  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. // The chado_xxxx properties are added to the entity in the
  175. // tripal_chado_entity_load() hook which unfortunately is called after
  176. // attaching fields. So, we may not have these properties. If that's
  177. // the case we can get them by querying the chado_entity table directly.
  178. // The chado_xxxx properites will be here in the case of syncing
  179. // records.
  180. // TODO: perhaps we should add a hook_entity_preattach() hook?
  181. if (property_exists($entity, 'chado_table')) {
  182. // Get the base table and record id for the fields of this entity.
  183. $base_table = $entity->chado_table;
  184. $type_field = $entity->chado_column;
  185. $record_id = $entity->chado_record_id;
  186. }
  187. else {
  188. // Get the base table and record id for the fields of this entity.
  189. $details = db_select('chado_entity', 'ce')
  190. ->fields('ce')
  191. ->condition('entity_id', $entity->id)
  192. ->execute()
  193. ->fetchObject();
  194. if (!$details) {
  195. // TODO: what to do if record is missing!
  196. }
  197. // Get some values needed for loading the values from Chado.
  198. $base_table = $details->data_table;
  199. $type_field = $details->field;
  200. $record_id = $details->record_id;
  201. }
  202. // Get this table's schema.
  203. $schema = chado_get_schema($base_table);
  204. $pkey_field = $schema['primary key'][0];
  205. // Get the base record if one exists
  206. $columns = array('*');
  207. $match = array($pkey_field => $record_id);
  208. $record = chado_generate_var($base_table, $match);
  209. $entity->chado_record = $record;
  210. // For now, expand all 'text' fields.
  211. // TODO: we want to be a bit smarter and allow the user to configure this
  212. // for now we'll expand.
  213. foreach ($schema['fields'] as $field_name => $details) {
  214. if ($schema['fields'][$field_name]['type'] == 'text') {
  215. $record = chado_expand_var($record, 'field', $base_table . '.' . $field_name);
  216. }
  217. }
  218. // Iterate through the entity's fields so we can get the column names
  219. // that need to be selected from each of the tables represented.
  220. $tables = array();
  221. foreach ($fields as $field_id => $ids) {
  222. // By the time this hook runs, the relevant field definitions have been
  223. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  224. // on each field individually is more efficient than loading all fields in
  225. // memory upfront with field_info_field_by_ids().
  226. $field = field_info_field_by_id($field_id);
  227. $field_name = $field['field_name'];
  228. $field_type = $field['type'];
  229. $field_module = $field['module'];
  230. // Skip fields that don't map to a Chado table (e.g. kvproperty_adder).
  231. if (!array_key_exists('settings', $field) or !array_key_exists('chado_table', $field['settings'])) {
  232. continue;
  233. }
  234. // Get the Chado table and column for this field.
  235. $field_table = $field['settings']['chado_table'];
  236. $field_column = $field['settings']['chado_column'];
  237. // There are only two types of fields: 1) fields that represent a single
  238. // column of the base table, or 2) fields that represent a linked record
  239. // in a many-to-one relationship with the base table.
  240. // Type 1: fields from base tables.
  241. if ($field_table == $base_table) {
  242. // Set an empty value by default, and if there is a record, then update.
  243. $entity->{$field_name}['und'][0]['value'] = '';
  244. if ($record and property_exists($record, $field_column)) {
  245. // If the field column is an object then it's a FK to another table.
  246. // and because $record object is created by the chado_generate_var()
  247. // function we must go one more level deeper to get the value
  248. if (is_object($record->$field_column)) {
  249. $entity->{$field_name}['und'][0][$field_table . '__' . $field_column] = $record->$field_column->$field_column;
  250. }
  251. else {
  252. // For non FK fields we'll make the field value be the same
  253. // as the column value.
  254. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  255. $entity->{$field_name}['und'][0][$field_table . '__' . $field_column] = $record->$field_column;
  256. }
  257. }
  258. // Allow the creating module to alter the value if desired. The
  259. // module should do this if the field has any other form elements
  260. // that need populationg besides the value which was set above.
  261. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  262. if (preg_match('/^chado/', $field_type) and class_exists($field_type)) {
  263. $field_obj = new $field_type();
  264. $field_obj->load($field, $entity, array('record' => $record));
  265. }
  266. $load_function = $field_type . '_load';
  267. if (function_exists($load_function)) {
  268. $load_function($field, $entity, $base_table, $record);
  269. }
  270. }
  271. // Type 2: fields for linked records. These fields will have any number
  272. // of form elements that might need populating so we'll offload the
  273. // loading of these fields to the field itself.
  274. if ($field_table != $base_table) {
  275. // Set an empty value by default, and let the hook function update it.
  276. $entity->{$field_name}['und'][0]['value'] = '';
  277. $load_function = $field_type . '_load';
  278. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  279. if (preg_match('/^chado/', $field_type) and class_exists($field_type)) {
  280. $field_obj = new $field_type();
  281. if (method_exists($field_obj, 'load')) {
  282. $field_obj->load($field, $entity, array('record' => $record));
  283. }
  284. }
  285. if (function_exists($load_function)) {
  286. $load_function($field, $entity, $base_table, $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. $new_fields = array();
  297. // Iterate through all of the fields and organize them into a
  298. // new fields array keyed by the table name
  299. foreach ($fields as $field_id => $ids) {
  300. // Get the field name and information about it.
  301. $field = field_info_field_by_id($field_id);
  302. $field_name = $field['field_name'];
  303. // Some fields (e.g. chado_linker_cvterm_adder) don't add data to
  304. // Chado so they don't have a table, but they are still attached to the
  305. // entity. Just skip these.
  306. if (!array_key_exists('chado_table', $field['settings'])) {
  307. continue;
  308. }
  309. $chado_table = $field['settings']['chado_table'];
  310. $chado_column = $field['settings']['chado_column'];
  311. // Iterate through the field's items. Fields with cardinality ($delta) > 1
  312. // are multi-valued.
  313. $items = field_get_items($entity_type, $entity, $field_name);
  314. foreach ($items as $delta => $item) {
  315. foreach ($item as $item_name => $value) {
  316. $matches = array();
  317. if (preg_match('/^(.*?)__(.*?)$/', $item_name, $matches)) {
  318. $table_name = $matches[1];
  319. $column_name = $matches[2];
  320. // Is this a nested FK field? If so break it down into a sub array.
  321. if (preg_match('/^(.*?)--(.*?)$/', $column_name, $matches)) {
  322. $parent_item_name = $matches[1];
  323. $sub_item_name = $matches[2];
  324. $sub_item = tripal_chado_field_storage_expand_field($sub_item_name, $value);
  325. if (count(array_keys($sub_item))) {
  326. // If we've already encountered this table and column then we've
  327. // already seen the numeric FK value or we've already added a
  328. // subcolumn. If the former we want to convert this to an array
  329. // so we can add the details.
  330. if (!array_key_exists($table_name, $new_fields) or
  331. !array_key_exists($delta, $new_fields[$table_name]) or
  332. !array_key_exists($parent_item_name, $new_fields[$table_name][$delta]) or
  333. !is_array($new_fields[$table_name][$delta][$parent_item_name])) {
  334. $new_fields[$table_name][$delta][$parent_item_name] = array();
  335. }
  336. $new_fields[$table_name][$delta][$parent_item_name] += $sub_item;
  337. }
  338. }
  339. else {
  340. // If not seen this table and column then just add it. If we've
  341. // already seen it then it means it's a FK field and we've already
  342. // added subfields so do nothing.
  343. if (!array_key_exists($table_name, $new_fields) or
  344. !array_key_exists($delta, $new_fields[$table_name]) or
  345. !array_key_exists($column_name, $new_fields[$table_name][$delta])) {
  346. $new_fields[$table_name][$delta][$column_name] = $value;
  347. }
  348. }
  349. }
  350. }
  351. // If there is no value set for the field using the
  352. // [table_name]__[field name] naming schema then check if a 'value' item
  353. // is present and if so use that.
  354. if ((!array_key_exists($chado_table, $new_fields) or
  355. !array_key_exists($delta, $new_fields[$chado_table]) or
  356. !array_key_exists($chado_column, $new_fields[$chado_table][$delta])) and
  357. array_key_exists('value', $items[$delta]) and
  358. !is_array($items[$delta]['value'])) {
  359. $new_fields[$chado_table][$delta][$chado_column] = $items[$delta]['value'];
  360. }
  361. }
  362. }
  363. return $new_fields;
  364. }
  365. /**
  366. * Recurses through a field's item name breaking it into a nested array.
  367. *
  368. *
  369. */
  370. function tripal_chado_field_storage_expand_field($item_name, $value) {
  371. $matches = array();
  372. if (preg_match('/^(.*?)--(.*?)$/', $item_name, $matches)) {
  373. $parent_item_name = $matches[1];
  374. $sub_item_name = $matches[2];
  375. $sub_item = tripal_chado_field_storage_expand_field($sub_item_name, $value);
  376. return array($parent_item_name => $sub_item);
  377. }
  378. else {
  379. return array($item_name => $value);
  380. }
  381. }
  382. /**
  383. * Implements hook_field_storage_query().
  384. *
  385. * Used by EntityFieldQuery to find the entities having certain field values.
  386. *
  387. * We do not support use of the EntityFieldQuery API for Tripal based fields
  388. * because EFQ doesn't support when multiple storage backends are used. Instead
  389. * use the TripalFieldQuery class and implement the hook_storage_tquery()
  390. * function.
  391. */
  392. function tripal_chado_field_storage_query($query) {
  393. }
  394. /**
  395. * Implements hook_field_storage_tquery().
  396. *
  397. * Used by TripalFieldQuery to find the entities having certain field values.
  398. *
  399. * @param $conditions
  400. */
  401. function tripal_chado_field_storage_tquery($conditions) {
  402. $filter = array();
  403. foreach ($conditions as $index => $condition) {
  404. $field = $condition['field'];
  405. $field_type = $field['type'];
  406. $field_module = $field['module'];
  407. $settings = $field['settings'];
  408. $chado_table = $settings['chado_table'];
  409. $chado_column = $settings['chado_column'];
  410. // Allow the creating module to alter the value if desired.
  411. $value = '';
  412. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  413. if (preg_match('/^chado/', $field_type) and class_exists($field_type)) {
  414. $field_obj = new $field_type();
  415. if (method_exists($field_obj, 'query')) {
  416. $value = $field_obj->query($condition);
  417. }
  418. }
  419. // If there is no field to rewrite the value then use defaults.
  420. else {
  421. $value = $condition['value'];
  422. }
  423. // use the appropriate operator.
  424. $operator = $condition['operator'];
  425. switch ($operator) {
  426. case '=':
  427. $filter[$chado_table][$chado_column] = $condition['value'];
  428. break;
  429. case '>':
  430. case '>=':
  431. case '<':
  432. case '<=':
  433. $filter[$chado_table][$chado_column] = array(
  434. 'op' => $operator,
  435. 'data' => $value,
  436. );
  437. break;
  438. case '<>':
  439. $filter[$chado_table][$chado_column] = array(
  440. 'op' => 'NOT',
  441. 'data' => $value,
  442. );
  443. break;
  444. case 'CONTAINS':
  445. break;
  446. $filter[$chado_table][$chado_column] = array(
  447. 'op' => 'LIKE',
  448. 'data' => '%' . $value . '%',
  449. );
  450. case 'STARTS WITH':
  451. $filter[$chado_table][$chado_column] = array(
  452. 'op' => 'LIKE',
  453. 'data' => $value . '%',
  454. );
  455. break;
  456. default:
  457. // unrecognized operation.
  458. break;
  459. }
  460. }
  461. // Iterate through the filters and perform the query
  462. $entity_ids = array();
  463. foreach ($filter as $chado_table => $values) {
  464. // First get the matching record IDs from the Chado table.
  465. $schema = chado_get_schema($chado_table);
  466. $pkey = $schema['primary key'][0];
  467. $results = chado_select_record($chado_table, array($pkey), $values);
  468. $record_ids = array();
  469. foreach ($results as $result) {
  470. $record_ids[] = $result->$pkey;
  471. }
  472. // Next look for matching IDs in the chado_entity table.
  473. $filter_ids = array();
  474. $results = db_select('chado_entity', 'CE')
  475. ->fields('CE', array('entity_id'))
  476. ->condition('record_id', $record_ids)
  477. ->execute();
  478. while ($result = $results->fetchObject()) {
  479. $filter_ids[] = $result->entity_id;
  480. }
  481. // Take the intersection of IDs in this filter with those in the
  482. // final $entity_ids;
  483. if (count($entity_ids) == 0) {
  484. $entity_ids = $filter_ids;
  485. }
  486. else {
  487. $entity_ids = array_intersect($entity_ids, $filter_ids);
  488. }
  489. }
  490. return $entity_ids;
  491. }