tripal_chado.field_storage.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. // Get the base table, type field and record_id from the entity.
  28. $base_table = $entity->chado_table;
  29. $type_field = $entity->chado_column;
  30. $record = $entity->chado_record;
  31. $record_id = $entity->chado_record_id;
  32. // Convert the fields into a key/value list of fields and their values.
  33. $field_vals = tripal_chado_field_storage_unnest_fields($fields, $entity_type, $entity);
  34. // Recursively write fields for the base table.
  35. $record_id = tripal_chado_field_storage_write_recursive($entity_type, $entity, $term,
  36. $op, $field_vals, $base_table, $base_table, $type_field, $record_id);
  37. // If this is an insert then add the chado_entity record.
  38. if ($op == FIELD_STORAGE_INSERT) {
  39. // Add a record to the chado_entity table so that the data for the
  40. // fields can be pulled from Chado when loaded the next time.
  41. $record = array(
  42. 'entity_id' => $entity->id,
  43. 'record_id' => $record_id,
  44. 'data_table' => $base_table,
  45. 'type_table' => $base_table,
  46. 'field' => $type_field,
  47. );
  48. $success = drupal_write_record('chado_entity', $record);
  49. if (!$success) {
  50. drupal_set_message('Unable to insert new Chado entity.', 'error');
  51. }
  52. }
  53. // Now that we have handled the base table, we need to handle fields that
  54. // are not part of the base table.
  55. foreach ($fields as $field_id) {
  56. // Get the field using the id.
  57. $field = field_info_field_by_id($field_id);
  58. $field_name = $field['field_name'];
  59. // If the field has a chado_table setting then we can try to write.
  60. if (array_key_exists('settings', $field) and array_key_exists('chado_table', $field['settings'])) {
  61. // Skip fields that use the base table, as we've already handled those.
  62. if ($field['settings']['chado_table'] != $base_table){
  63. $field_table = $field['settings']['chado_table'];
  64. // Iterate through each record.
  65. foreach ($field_vals[$field_name] as $delta => $fvals) {
  66. tripal_chado_field_storage_write_recursive($entity_type, $entity, $term,
  67. $op, $fvals, $base_table, $field_table);
  68. }
  69. }
  70. }
  71. }
  72. }
  73. /**
  74. *
  75. * @param $entity_type
  76. * @param $entity
  77. * @param $op
  78. * @param $field_vals
  79. * @param $tablename
  80. * @param $type_field
  81. * @param $record_id
  82. * @param $depth
  83. * @throws Exception
  84. * @return
  85. * The record_id of the table if a matching record exists.
  86. */
  87. function tripal_chado_field_storage_write_recursive($entity_type, $entity, $term,
  88. $op, $field_vals, $base_table, $tablename, $type_field = NULL,
  89. $record_id = NULL, $depth = 0) {
  90. // Intialize the values array.
  91. $values = array();
  92. // Get the schema for this table so that we can identify the primary key
  93. // and foreign keys.
  94. $schema = chado_get_schema($tablename);
  95. $pkey_field = $schema['primary key'][0];
  96. $fkey_fields = $schema['foreign keys'];
  97. $fkey_fields_list = array();
  98. $fkey_base_linker = NULL;
  99. // STEP 1: Recurse on the FK fields.
  100. // Loop through the foreign keys so that we can recurse on those first.
  101. foreach ($fkey_fields as $fk_table => $details) {
  102. foreach ($details['columns'] as $local_id => $remote_id) {
  103. // If this is the base table then do not recurse on the type_id.
  104. if ($tablename == $base_table && $local_id == $type_field) {
  105. $values[$local_id] = $term->details['cvterm']->cvterm_id;
  106. continue;
  107. }
  108. // If this is not the base table then do not recurse on the FK field
  109. // that links this table to the base table.
  110. if ($tablename != $base_table && $details['table'] == $base_table) {
  111. $fkey_base_linker = $local_id;
  112. continue;
  113. }
  114. // Get the value of the FK field as provided by the user.
  115. $fk_val = NULL;
  116. $fk_vals = array();
  117. $fk_field_name = $tablename . '__' . $local_id;
  118. if (array_key_exists($fk_field_name, $field_vals)) {
  119. $fk_val = $field_vals[$fk_field_name][0]['value'];
  120. $fk_vals = $field_vals[$fk_field_name][0];
  121. unset($fk_vals['value']);
  122. }
  123. // Don't recurse if the value of the FK field is set to NULL. The
  124. // Tripal Chado API value for NULL is '__NULL__'.
  125. if ($fk_val == "__NULL__") {
  126. $values[$local_id] = $fk_val;
  127. continue;
  128. }
  129. // Don't recuse if there are no fkvals.
  130. if (count(array_keys($fk_vals)) == 0) {
  131. continue;
  132. }
  133. // Keep track of the FK fields so that in STEP 2 we don't have to
  134. // loop through the $fk_fields again.
  135. $fkey_fields_list[] = $local_id;
  136. // Recurse on the FK field. Pass in the ID for the FK field if one
  137. // exists in the $field_vals;
  138. $fk_val = tripal_chado_field_storage_write_recursive($entity_type,
  139. $entity, $term, $op, $fk_vals, $base_table, $fk_table, NULL, $fk_val, $depth + 1);
  140. if (isset($fk_val) and $fk_val != '' and $fk_val != 0) {
  141. $values[$local_id] = $fk_val;
  142. }
  143. }
  144. }
  145. // STEP 2: Loop through the non FK fields.
  146. // Loop through the fields passed to the function and find any that
  147. // are for this table. Then add their values to the $values array.
  148. foreach ($field_vals as $field_name => $items) {
  149. if (preg_match('/^' . $tablename . '__(.*)/', $field_name, $matches)) {
  150. $chado_field = $matches[1];
  151. // Skip the PKey field. We won't ever insert a primary key and if
  152. // one is provided in the fields then we use it for matching on an
  153. // update. We don't add it to the $values array in either case.
  154. if ($chado_field == $pkey_field) {
  155. continue;
  156. }
  157. // Skip FK fields as those should already have been dealt with the
  158. // recursive code above.
  159. if (in_array($chado_field, $fkey_fields_list)) {
  160. continue;
  161. }
  162. // If the value is empty then exclude this field
  163. if (!$items[0]['value']) {
  164. continue;
  165. }
  166. // Add the value of the field to the $values arr for later insert/update.
  167. $values[$chado_field] = $items[0]['value'];
  168. }
  169. }
  170. // STEP 3: Insert/Update the record.
  171. // If there are no values then return.
  172. if (count($values) == 0) {
  173. return $record_id;
  174. }
  175. // If we don't have an incoming record ID then this is an insert.
  176. if ($record_id == NULL) {
  177. // STEP 3a: Before inserting, we want to make sure the record does not
  178. // already exist. Using the unique constraint check for a matching record.
  179. $options = array('is_duplicate' => TRUE);
  180. $is_duplicate = chado_select_record($tablename, array('*'), $values, $options);
  181. if($is_duplicate) {
  182. $record = chado_select_record($tablename, array('*'), $values);
  183. return $record[0]->$pkey_field;
  184. }
  185. // STEP 3b: Insert the reocrd
  186. // Insert the values array as a new record in the table.
  187. $record = chado_insert_record($tablename, $values);
  188. if ($record === FALSE) {
  189. throw new Exception('Could not insert Chado record into table: "' . $tablename . '".');
  190. }
  191. $record_id = $record[$pkey_field];
  192. }
  193. // We have an incoming record_id so this is an update.
  194. else {
  195. $match[$pkey_field] = $record_id;
  196. if (!chado_update_record($tablename, $match, $values)) {
  197. drupal_set_message("Could not update Chado record in table: $tablename.", 'error');
  198. }
  199. }
  200. return $record_id;
  201. }
  202. /**
  203. * Implements hook_field_storage_load().
  204. *
  205. * Responsible for loading the fields from the Chado database and adding
  206. * their values to the entity.
  207. */
  208. function tripal_chado_field_storage_load($entity_type, $entities, $age,
  209. $fields, $options) {
  210. $load_current = $age == FIELD_LOAD_CURRENT;
  211. global $language;
  212. $langcode = $language->language;
  213. foreach ($entities as $id => $entity) {
  214. // Get the base table and record id for the fields of this entity.
  215. $details = db_select('chado_entity', 'ce')
  216. ->fields('ce')
  217. ->condition('entity_id', $entity->id)
  218. ->execute()
  219. ->fetchObject();
  220. if (!$details) {
  221. // TODO: what to do if record is missing!
  222. }
  223. // Get some values needed for loading the values from Chado.
  224. $base_table = $details->data_table;
  225. $type_field = $details->field;
  226. $record_id = $details->record_id;
  227. // Get this table's schema.
  228. $schema = chado_get_schema($base_table);
  229. $pkey_field = $schema['primary key'][0];
  230. // Get the base record if one exists
  231. $columns = array('*');
  232. $match = array($pkey_field => $record_id);
  233. $record = chado_generate_var($base_table, $match);
  234. // For now, expand all 'text' fields.
  235. // TODO: we want to be a bit smarter and allow the user to configure this
  236. // for now we'll expand.
  237. foreach ($schema['fields'] as $field_name => $details) {
  238. if ($schema['fields'][$field_name]['type'] == 'text') {
  239. $record = chado_expand_var($record, 'field', $base_table . '.' . $field_name);
  240. }
  241. }
  242. // Iterate through the entity's fields so we can get the column names
  243. // that need to be selected from each of the tables represented.
  244. $tables = array();
  245. foreach ($fields as $field_id => $ids) {
  246. // By the time this hook runs, the relevant field definitions have been
  247. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  248. // on each field individually is more efficient than loading all fields in
  249. // memory upfront with field_info_field_by_ids().
  250. $field = field_info_field_by_id($field_id);
  251. $field_name = $field['field_name'];
  252. $field_type = $field['type'];
  253. $field_module = $field['module'];
  254. // Skip fields that don't map to a Chado table (e.g. kvproperty_adder).
  255. if (!array_key_exists('settings', $field) or !array_key_exists('chado_table', $field['settings'])) {
  256. continue;
  257. }
  258. // Get the Chado table and column for this field.
  259. $field_table = $field['settings']['chado_table'];
  260. $field_column = $field['settings']['chado_column'];
  261. // There are only two types of fields: 1) fields that represent a single
  262. // column of the base table, or 2) fields that represent a linked record
  263. // in a many-to-one relationship with the base table.
  264. // Type 1: fields from base tables.
  265. if ($field_table == $base_table) {
  266. // Set an empty value by default, and if there is a record, then update.
  267. $entity->{$field_name}['und'][0]['value'] = '';
  268. if ($record and property_exists($record, $field_column)) {
  269. // If the field column is an object then it's a FK to another table.
  270. // and because $record object is created by the chado_generate_var()
  271. // function we must go one more level deeper to get the value
  272. if (is_object($record->$field_column)) {
  273. $entity->{$field_name}['und'][0]['value'] = $record->$field_column->$field_column;
  274. }
  275. else {
  276. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  277. }
  278. }
  279. // Allow the creating module to alter the value if desired. The
  280. // module should do this if the field has any other form elements
  281. // that need populationg besides the default value.
  282. $load_function = $field_module . '_' . $field_type . '_field_load';
  283. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  284. if (function_exists($load_function)) {
  285. $load_function($field, $entity, $base_table, $record);
  286. }
  287. }
  288. // Type 2: fields for linked records. These fields will have any number
  289. // of form elements that might need populating so we'll offload the
  290. // loading of these fields to the field itself.
  291. if ($field_table != $base_table) {
  292. // Set an empty value by default, and let the hook function update it.
  293. $entity->{$field_name}['und'][0]['value'] = '';
  294. $load_function = $field_module . '_' . $field_type . '_field_load';
  295. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  296. if (function_exists($load_function)) {
  297. $load_function($field, $entity, $base_table, $record);
  298. }
  299. }
  300. } // end: foreach ($fields as $field_id => $ids) {
  301. } // end: foreach ($entities as $id => $entity) {
  302. }
  303. /**
  304. * Iterates through all of the fields reformats to a key/value array.
  305. *
  306. * @param $fields
  307. */
  308. function tripal_chado_field_storage_unnest_fields($fields, $entity_type, $entity) {
  309. $new_fields = array();
  310. // Iterate through all of the fields.
  311. foreach ($fields as $field_id => $ids) {
  312. // Get the field name and all of it's items.
  313. $field = field_info_field_by_id($field_id);
  314. $field_name = $field['field_name'];
  315. $items = field_get_items($entity_type, $entity, $field_name);
  316. // Iterate through the field's items. Fields with cardinality ($delta) > 1
  317. // are multi-valued.
  318. foreach ($items as $delta => $item) {
  319. foreach ($item as $item_name => $value) {
  320. if ($item_name == 'value') {
  321. $new_fields[$field_name][$delta]['value'] = $value;
  322. continue;
  323. }
  324. $matches = array();
  325. if (preg_match('/^(.*?)__.*?$/', $item_name, $matches)) {
  326. $table_name = $matches[1];
  327. $new_fields[$field_name][$delta][$item_name][0]['value'] = $value;
  328. }
  329. }
  330. }
  331. }
  332. return $new_fields;
  333. }
  334. /**
  335. * Implements hook_field_storage_query().
  336. *
  337. * Used by EntityFieldQuery to find the entities having certain entity
  338. * and field conditions and sort them in the given field order.
  339. *
  340. * NOTE: This function needs to exist or errors are triggered but so far it doesn't
  341. * appear to actually need to do anything...
  342. */
  343. function tripal_chado_field_storage_query($query) { }