tripal_chado.field_storage.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. $base_schema = chado_get_schema($base_table);
  33. $base_pkey = $base_schema['primary key'][0];
  34. // Convert the fields into a key/value list of fields and their values.
  35. $field_vals = tripal_chado_field_storage_merge_fields($fields, $entity_type, $entity);
  36. // Write the record for the base table. If this is an update then we'll have
  37. // the record_id and we need to add that to our values array.
  38. $values = $field_vals[$base_table][0];
  39. if ($record_id) {
  40. $values[$base_pkey] = $record_id;
  41. }
  42. $base_record_id = tripal_chado_field_storage_write_table($base_table, $values);
  43. // If this is an insert then add the chado_entity record.
  44. if ($op == FIELD_STORAGE_INSERT) {
  45. // Add a record to the chado_entity table so that the data for the
  46. // fields can be pulled from Chado when loaded the next time.
  47. $record = array(
  48. 'entity_id' => $entity->id,
  49. 'record_id' => $record_id,
  50. 'data_table' => $base_table,
  51. 'type_table' => $base_table,
  52. 'field' => $type_field,
  53. );
  54. $success = drupal_write_record('chado_entity', $record);
  55. if (!$success) {
  56. drupal_set_message('Unable to insert new Chado entity.', 'error');
  57. }
  58. }
  59. // Now that we have handled the base table, we need to handle linking tables.
  60. foreach ($field_vals as $table_name => $details) {
  61. // Skip the base table as we've already dealt with it.
  62. if ($table_name == $base_table) {
  63. continue;
  64. }
  65. foreach ($details as $delta => $values) {
  66. $record_id = tripal_chado_field_storage_write_table($table_name, $values);
  67. }
  68. }
  69. }
  70. /**
  71. * Write (inserts/oupdates) a nested array of values for a table.
  72. *
  73. * The $values array is of the same format used by chado_insert_record() and
  74. * chado_update_record(). However, both of those methods will use any nested
  75. * arrays (i.e. representing foreign keys) to select an appropriate record ID
  76. * that can be substituted as the value. Here, the nested arrays are
  77. * either inserted or updated as well, but the choice is determined if the
  78. * primary key value is present. If present an update occurs, if not present
  79. * then an insert occurs.
  80. *
  81. * This function is recursive and nested arrays from the lowest point of the
  82. * "tree" are dealt with first.
  83. *
  84. * @param $table_name
  85. * The name of the table on which the insertion/update is performed.
  86. * @param $values
  87. * The values array for the insertion.
  88. * @throws Exception
  89. * @return
  90. * The unique record ID.
  91. */
  92. function tripal_chado_field_storage_write_table($table_name, $values) {
  93. $schema = chado_get_schema($table_name);
  94. $fkeys = $schema['foreign keys'];
  95. $pkey = $schema['primary key'][0];
  96. // Before inserting or updating this table, recruse if there are any
  97. // nested FK array values.
  98. foreach ($values as $column => $value) {
  99. // If this value is an array then it must be a FK... let's recurse.
  100. if (is_array($value)) {
  101. // Find the name of the FK table for this column.
  102. $fktable_name = '';
  103. foreach ($fkeys as $fktable => $details) {
  104. foreach ($details['columns'] as $fkey_lcolumn => $fkey_rcolumn) {
  105. if ($fkey_lcolumn == $column) {
  106. $fktable_name = $fktable;
  107. }
  108. }
  109. }
  110. // Recurse on this recod.
  111. $record_id = tripal_chado_field_storage_write_table($fktable_name, $values[$column]);
  112. $values[$column] = $record_id;
  113. }
  114. }
  115. // Fields with a cardinality greater than 1 will often submit an
  116. // empty form. We want to remove these empty submissions. We can detect
  117. // them if all of the fields are empty.
  118. $num_empty = 0;
  119. foreach ($values as $column => $value) {
  120. if (!$value) {
  121. $num_empty++;
  122. }
  123. }
  124. if ($num_empty == count(array_keys($values))) {
  125. return '';
  126. }
  127. // If the primary key column has a value then this will be an udpate,
  128. // otherwise it's an insert.
  129. if (!$values[$pkey]) {
  130. // Before inserting, we want to make sure the record does not
  131. // already exist. Using the unique constraint check for a matching record.
  132. $options = array('is_duplicate' => TRUE);
  133. $is_duplicate = chado_select_record($table_name, array('*'), $values, $options);
  134. if($is_duplicate) {
  135. $record = chado_select_record($table_name, array('*'), $values);
  136. return $record[0]->$pkey_field;
  137. }
  138. // Insert the values array as a new record in the table.
  139. $record = chado_insert_record($table_name, $values);
  140. if ($record === FALSE) {
  141. throw new Exception('Could not insert Chado record into table: "' . $tablename . '".');
  142. }
  143. return $record_id = $record[$pkey_field];
  144. }
  145. // We have an incoming record_id so this is an update.
  146. else {
  147. // TODO: what if the unique constraint matches another record? That is
  148. // not being tested for here.
  149. $match[$pkey] = $values[$pkey];
  150. if (!chado_update_record($table_name, $match, $values)) {
  151. drupal_set_message("Could not update Chado record in table: $tablename.", 'error');
  152. }
  153. return $values[$pkey];
  154. }
  155. }
  156. /**
  157. * Implements hook_field_storage_load().
  158. *
  159. * Responsible for loading the fields from the Chado database and adding
  160. * their values to the entity.
  161. */
  162. function tripal_chado_field_storage_load($entity_type, $entities, $age,
  163. $fields, $options) {
  164. $load_current = $age == FIELD_LOAD_CURRENT;
  165. global $language;
  166. $langcode = $language->language;
  167. foreach ($entities as $id => $entity) {
  168. // Get the base table and record id for the fields of this entity.
  169. $details = db_select('chado_entity', 'ce')
  170. ->fields('ce')
  171. ->condition('entity_id', $entity->id)
  172. ->execute()
  173. ->fetchObject();
  174. if (!$details) {
  175. // TODO: what to do if record is missing!
  176. }
  177. // Get some values needed for loading the values from Chado.
  178. $base_table = $details->data_table;
  179. $type_field = $details->field;
  180. $record_id = $details->record_id;
  181. // Get this table's schema.
  182. $schema = chado_get_schema($base_table);
  183. $pkey_field = $schema['primary key'][0];
  184. // Get the base record if one exists
  185. $columns = array('*');
  186. $match = array($pkey_field => $record_id);
  187. $record = chado_generate_var($base_table, $match);
  188. $entity->chado_record = $record;
  189. // For now, expand all 'text' fields.
  190. // TODO: we want to be a bit smarter and allow the user to configure this
  191. // for now we'll expand.
  192. foreach ($schema['fields'] as $field_name => $details) {
  193. if ($schema['fields'][$field_name]['type'] == 'text') {
  194. $record = chado_expand_var($record, 'field', $base_table . '.' . $field_name);
  195. }
  196. }
  197. // Iterate through the entity's fields so we can get the column names
  198. // that need to be selected from each of the tables represented.
  199. $tables = array();
  200. foreach ($fields as $field_id => $ids) {
  201. // By the time this hook runs, the relevant field definitions have been
  202. // populated and cached in FieldInfo, so calling field_info_field_by_id()
  203. // on each field individually is more efficient than loading all fields in
  204. // memory upfront with field_info_field_by_ids().
  205. $field = field_info_field_by_id($field_id);
  206. $field_name = $field['field_name'];
  207. $field_type = $field['type'];
  208. $field_module = $field['module'];
  209. // Skip fields that don't map to a Chado table (e.g. kvproperty_adder).
  210. if (!array_key_exists('settings', $field) or !array_key_exists('chado_table', $field['settings'])) {
  211. continue;
  212. }
  213. // Get the Chado table and column for this field.
  214. $field_table = $field['settings']['chado_table'];
  215. $field_column = $field['settings']['chado_column'];
  216. // There are only two types of fields: 1) fields that represent a single
  217. // column of the base table, or 2) fields that represent a linked record
  218. // in a many-to-one relationship with the base table.
  219. // Type 1: fields from base tables.
  220. if ($field_table == $base_table) {
  221. // Set an empty value by default, and if there is a record, then update.
  222. $entity->{$field_name}['und'][0]['value'] = '';
  223. if ($record and property_exists($record, $field_column)) {
  224. // If the field column is an object then it's a FK to another table.
  225. // and because $record object is created by the chado_generate_var()
  226. // function we must go one more level deeper to get the value
  227. if (is_object($record->$field_column)) {
  228. $entity->{$field_name}['und'][0][$field_table . '__' . $field_column] = $record->$field_column->$field_column;
  229. }
  230. else {
  231. // For non FK fields we'll make the field value be the same
  232. // as the column value.
  233. $entity->{$field_name}['und'][0]['value'] = $record->$field_column;
  234. $entity->{$field_name}['und'][0][$field_table . '__' . $field_column] = $record->$field_column;
  235. }
  236. }
  237. // Allow the creating module to alter the value if desired. The
  238. // module should do this if the field has any other form elements
  239. // that need populationg besides the value which was set above.
  240. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  241. if (preg_match('/^chado/', $field_type) and class_exists($field_type)) {
  242. $field_obj = new $field_type();
  243. $field_obj->load($field, $entity, array('record' => $record));
  244. }
  245. $load_function = $field_type . '_load';
  246. if (function_exists($load_function)) {
  247. $load_function($field, $entity, $base_table, $record);
  248. }
  249. }
  250. // Type 2: fields for linked records. These fields will have any number
  251. // of form elements that might need populating so we'll offload the
  252. // loading of these fields to the field itself.
  253. if ($field_table != $base_table) {
  254. // Set an empty value by default, and let the hook function update it.
  255. $entity->{$field_name}['und'][0]['value'] = '';
  256. $load_function = $field_type . '_load';
  257. module_load_include('inc', $field_module, 'includes/fields/' . $field_type);
  258. if (preg_match('/^chado/', $field_type) and class_exists($field_type)) {
  259. $field_obj = new $field_type();
  260. $field_obj->load($field, $entity, array('record' => $record));
  261. }
  262. if (function_exists($load_function)) {
  263. $load_function($field, $entity, $base_table, $record);
  264. }
  265. }
  266. } // end: foreach ($fields as $field_id => $ids) {
  267. } // end: foreach ($entities as $id => $entity) {
  268. }
  269. /**
  270. * Merges the values of all fields into a single array keyed by table name.
  271. */
  272. function tripal_chado_field_storage_merge_fields($fields, $entity_type, $entity) {
  273. $new_fields = array();
  274. // Iterate through all of the fields and organize them into a
  275. // new fields array keyed by the table name
  276. foreach ($fields as $field_id => $ids) {
  277. // Get the field name and information about it.
  278. $field = field_info_field_by_id($field_id);
  279. $field_name = $field['field_name'];
  280. // Some fields (e.g. chado_linker_cvterm_adder) don't add data to
  281. // Chado so they don't have a table, but they are still attached to the
  282. // entity. Just skip these.
  283. if (!array_key_exists('chado_table', $field['settings'])) {
  284. continue;
  285. }
  286. $chado_table = $field['settings']['chado_table'];
  287. $chado_column = $field['settings']['chado_column'];
  288. // Iterate through the field's items. Fields with cardinality ($delta) > 1
  289. // are multi-valued.
  290. $items = field_get_items($entity_type, $entity, $field_name);
  291. foreach ($items as $delta => $item) {
  292. foreach ($item as $item_name => $value) {
  293. $matches = array();
  294. if (preg_match('/^(.*?)__(.*?)$/', $item_name, $matches)) {
  295. $table_name = $matches[1];
  296. $column_name = $matches[2];
  297. // Is this a nested FK field? If so break it down into a sub array.
  298. if (preg_match('/^(.*?)--(.*?)$/', $column_name, $matches)) {
  299. $parent_item_name = $matches[1];
  300. $sub_item_name = $matches[2];
  301. $sub_item = tripal_chado_field_storage_expand_field($sub_item_name, $value);
  302. if (count(array_keys($sub_item))) {
  303. // If we've already encountered this table and column then we've
  304. // already seen the numeric FK value or we've already added a
  305. // subcolumn. If the former we want to convert this to an array
  306. // so we can add the details.
  307. if (!array_key_exists($table_name, $new_fields) or
  308. !array_key_exists($delta, $new_fields[$table_name]) or
  309. !array_key_exists($parent_item_name, $new_fields[$table_name][$delta]) or
  310. !is_array($new_fields[$table_name][$delta][$parent_item_name])) {
  311. $new_fields[$table_name][$delta][$parent_item_name] = array();
  312. }
  313. $new_fields[$table_name][$delta][$parent_item_name] += $sub_item;
  314. }
  315. }
  316. else {
  317. // If not seen this table and column then just add it. If we've
  318. // already seen it then it means it's a FK field and we've already
  319. // added subfields so do nothing.
  320. if (!array_key_exists($table_name, $new_fields) or
  321. !array_key_exists($delta, $new_fields[$table_name]) or
  322. !array_key_exists($column_name, $new_fields[$table_name][$delta])) {
  323. $new_fields[$table_name][$delta][$column_name] = $value;
  324. }
  325. }
  326. }
  327. }
  328. // If there is no value set for the field using the
  329. // [table_name]__[field name] naming schema then check if a 'value' item
  330. // is present and if so use that.
  331. if ((!array_key_exists($chado_table, $new_fields) or
  332. !array_key_exists($delta, $new_fields[$chado_table]) or
  333. !array_key_exists($chado_column, $new_fields[$chado_table][$delta])) and
  334. array_key_exists('value', $items[$delta]) and
  335. !is_array($items[$delta]['value'])) {
  336. $new_fields[$chado_table][$delta][$chado_column] = $items[$delta]['value'];
  337. }
  338. }
  339. }
  340. return $new_fields;
  341. }
  342. /**
  343. * Recurses through a field's item name breaking it into a nested array.
  344. *
  345. *
  346. */
  347. function tripal_chado_field_storage_expand_field($item_name, $value) {
  348. $matches = array();
  349. if (preg_match('/^(.*?)--(.*?)$/', $item_name, $matches)) {
  350. $parent_item_name = $matches[1];
  351. $sub_item_name = $matches[2];
  352. $sub_item = tripal_chado_field_storage_expand_field($sub_item_name, $value);
  353. return array($parent_item_name => $sub_item);
  354. }
  355. else {
  356. return array($item_name => $value);
  357. }
  358. }
  359. /**
  360. * Implements hook_field_storage_query().
  361. *
  362. * Used by EntityFieldQuery to find the entities having certain entity
  363. * and field conditions and sort them in the given field order.
  364. *
  365. * NOTE: This function needs to exist or errors are triggered but so far it doesn't
  366. * appear to actually need to do anything...
  367. */
  368. function tripal_chado_field_storage_query($query) {
  369. $fieldConditions = $query->fieldConditions;
  370. foreach ($fieldConditions as $condition) {
  371. $field = $condition['field'];
  372. $field_name = $field['field_name'];
  373. $column = $condition['column'];
  374. }
  375. }