tripal_bulk_loader.loader.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. <?php
  2. /**
  3. * Add Loader Job Form
  4. *
  5. * This form is meant to be included on the node page to allow users to submit/re-submit
  6. * loading jobs
  7. */
  8. function tripal_bulk_loader_add_loader_job_form ($form_state, $node) {
  9. $form = array();
  10. $form['nid'] = array(
  11. '#type' => 'hidden',
  12. '#value' => $node->nid,
  13. );
  14. $form['file'] = array(
  15. '#type' => 'hidden',
  16. '#value' => $node->file
  17. );
  18. $form['job_id'] = array(
  19. '#type' => 'hidden',
  20. '#value' => $node->job_id,
  21. );
  22. $form['submit'] = array(
  23. '#type' => 'submit',
  24. '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
  25. );
  26. $form['submit-cancel'] = array(
  27. '#type' => ($node->job_id)? 'submit' : 'hidden',
  28. '#value' => 'Cancel Job',
  29. );
  30. $form['submit-revert'] = array(
  31. '#type' => ($node->job_id) ? 'submit' : 'hidden',
  32. '#value' => 'Revert',
  33. );
  34. return $form;
  35. }
  36. /**
  37. * Add Loader Job Form (Submit)
  38. */
  39. function tripal_bulk_loader_add_loader_job_form_submit ($form, $form_state) {
  40. global $user;
  41. if (preg_match('/Submit Job/', $form_state['values']['op'])) {
  42. //Submit Tripal Job
  43. $job_args[1] = $form_state['values']['nid'];
  44. if (is_readable($form_state['values']['file'])) {
  45. $fname = basename($form_state['values']['file']);
  46. $job_id = tripal_add_job("Bulk Loading Job: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
  47. // add job_id to bulk_loader node
  48. $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
  49. } else {
  50. drupal_set_message("Can not open ".$form_state['values']['file'].". Job not scheduled.");
  51. }
  52. } elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
  53. tripal_jobs_rerun($form_state['values']['job_id']);
  54. } elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
  55. tripal_jobs_cancel($form_state['values']['job_id']);
  56. } elseif (preg_match('/Revert/', $form_state['values']['op'])) {
  57. // Remove the records from the database that were already inserted
  58. $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d', $form_state['values']['nid']);
  59. while ($r = db_fetch_object($resource)) {
  60. $ids = preg_split('/,/',$r->ids_inserted);
  61. db_query('DELETE FROM %s WHERE %s IN (%s)',$r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
  62. db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d',$r->tripal_bulk_loader_inserted_id);
  63. }
  64. }
  65. }
  66. /**
  67. * Tripal Bulk Loader
  68. *
  69. * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  70. * @param $nid
  71. * The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  72. * in the node (ie: template ID and file)
  73. *
  74. * Note: Instead of returning a value this function updates the tripal_bulk_loader.status and
  75. * Enters errors into tripal_bulk_loader_errors if they are encountered.
  76. */
  77. function tripal_bulk_loader_load_data($nid) {
  78. $node = node_load($nid);
  79. print "Template: ".$node->template->name." (".$node->template_id.")\n";
  80. print "File: ".$node->file."\n";
  81. // Prep Work ==================================================================================
  82. // Generate default values array
  83. $default_data = array();
  84. $field2column = array();
  85. $record2priority = array();
  86. foreach ($node->template->template_array as $priority => $record_array) {
  87. if (!is_array($record_array)) { continue; }
  88. foreach ($record_array['fields'] as $field_index => $field_array) {
  89. $default_data[$priority]['table'] = $record_array['table'];
  90. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
  91. $default_data[$priority]['record_id'] = $record_array['record_id'];
  92. $record2priority[$record_array['record_id']] = $priority;
  93. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  94. if (isset($field_array['regex'])) {
  95. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  96. }
  97. if (preg_match('/table field/', $field_array['type'])) {
  98. $default_data[$priority]['values_array'][$field_array['field']] = '';
  99. $default_data[$priority]['need_further_processing'] = TRUE;
  100. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  101. } elseif (preg_match('/constant/', $field_array['type'])) {
  102. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  103. } elseif (preg_match('/foreign key/', $field_array['type'])) {
  104. $default_data[$priority]['values_array'][$field_array['field']] = array();
  105. $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
  106. $default_data[$priority]['need_further_processing'] = TRUE;
  107. } else {
  108. print 'WARNING: Unsupported type: '. $field_array['type'] . ' for ' . $table . '.' . $field_array['field']."!\n";
  109. }
  110. } // end of foreach field
  111. } //end of foreach record
  112. //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
  113. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  114. // Parse File adding records as we go ========================================================
  115. $file_handle = fopen($node->file, 'r');
  116. if (preg_match('/(t|true|1)/', $node->file_has_header)) { fgets($file_handle, 4096); }
  117. $num_records = 0;
  118. $num_lines = 0;
  119. $num_errors = 0;
  120. while (!feof($file_handle)) {
  121. $line = array();
  122. $raw_line = fgets($file_handle, 4096);
  123. $raw_line = trim($raw_line);
  124. if (preg_match('/^\s*$/', $raw_line)) { continue; } // skips blank lines
  125. $line = preg_split("/\t/", $raw_line);
  126. $num_lines++;
  127. $data = $default_data;
  128. foreach ($data as $priority => $table_data) {
  129. $table = $table_data['table'];
  130. $values = $table_data['values_array'];
  131. //print 'default values:'.print_r($values,TRUE)."\n";
  132. if ($table_data['need_further_processing']) {
  133. $values = tripal_bulk_loader_add_spreadsheetdata_to_values ($values, $line, $field2column[$priority]);
  134. //print 'after spreadsheet values:'.print_r($values,TRUE)."\n";
  135. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
  136. //print 'after fk values:'.print_r($values,TRUE)."\n";
  137. }
  138. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
  139. //print 'after regex values:'.print_r($values,TRUE)."\n";
  140. if (!$values) {
  141. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Aborted due to error in previous record.';
  142. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  143. print "ERROR: ".$msg."\n";
  144. $data[$priority]['error'] = TRUE;
  145. }
  146. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  147. if (preg_match('/optional/', $table_array['mode'])) {
  148. // Check all db required fields are set
  149. $fields = $table_desc['fields'];
  150. foreach($fields as $field => $def){
  151. // a field is considered missing if it cannot be null and there is no default
  152. // value for it or it is of type 'serial'
  153. if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !isset($def['default']) and strcmp($def['type'],serial)!=0){
  154. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Missing Database Required Value: '.$table.'.'.$field;
  155. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  156. $data[$priority]['error'] = TRUE;
  157. }
  158. }
  159. } //end of if optional record
  160. // Check required fields are present
  161. foreach ($table_data['required'] as $field => $required) {
  162. if ($required) {
  163. if (!isset($values[$field])) {
  164. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Missing Template Required Value: '.$table.'.'.$field;
  165. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  166. $data[$priority]['error'] = TRUE;
  167. }
  168. }
  169. }
  170. // add new values array into the data array
  171. $data[$priority]['values_array'] = $values;
  172. // check if it is already inserted
  173. if ($table_data['inserted']) {
  174. continue;
  175. }
  176. // if there was an error already -> don't insert
  177. if ($data[$priority]['error']) {
  178. continue;
  179. }
  180. // if insert unique then check to ensure unique
  181. if (preg_match('/insert_unique/',$table_data['mode'])) {
  182. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record'=>TRUE));
  183. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  184. if ($unique > 0) {
  185. continue;
  186. }
  187. }
  188. if (!preg_match('/select/',$table_data['mode'])) {
  189. $record = tripal_core_chado_insert($table, $values);
  190. if (!$record) {
  191. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Unable to insert record into '.$table.' where values:'.print_r($values,TRUE);
  192. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  193. print "ERROR: ".$msg."\n";
  194. $data[$priority]['error'] = TRUE;
  195. } else {
  196. //add changes back to values array
  197. $data[$priority]['values_array'] = $record;
  198. $values = $record;
  199. // if mode=insert_once then ensure we only insert it once
  200. if (preg_match('/insert_once/',$table_data['mode'])) {
  201. $default_data[$priority]['inserted'] = TRUE;
  202. }
  203. // add to tripal_bulk_loader_inserted
  204. $insert_record = db_fetch_object(db_query(
  205. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  206. $table,
  207. $nid
  208. ));
  209. if ($insert_record) {
  210. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  211. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  212. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  213. } else {
  214. $insert_record = array(
  215. 'nid' => $nid,
  216. 'table_inserted_into' => $table,
  217. 'table_primary_key' => $table_desc['primary key'][0],
  218. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  219. );
  220. //print 'New: '.print_r($insert_record,TRUE)."\n";
  221. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  222. }//end of if insert record
  223. } //end of if insert was successful
  224. } else {
  225. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record'=>TRUE));
  226. if (!$exists) {
  227. // No record on select
  228. $msg = $table_data['record_id'].' ('.$table_data['mode'].') No Matching record in '.$table.' where values:'.print_r($values,TRUE);
  229. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  230. $data[$priority]['error'] = TRUE;
  231. }
  232. }
  233. } // end of foreach table in default data array
  234. } //end of foreach line of file
  235. // check that data was inserted and update job_status
  236. $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
  237. $result = db_fetch_object(db_query($sql, $nid));
  238. if ($result->num_tables > 0) {
  239. $node->job_status = 'Data Inserted';
  240. drupal_write_record('node',$node,'nid');
  241. }
  242. }
  243. /**
  244. * This function adds the file data to the values array
  245. *
  246. * @param $values
  247. * The default values array -contains all constants
  248. * @param $line
  249. * An array of values for the current line
  250. * @param $field2column
  251. * An array mapping values fields to line columns
  252. * @return
  253. * Supplemented values array
  254. */
  255. function tripal_bulk_loader_add_spreadsheetdata_to_values ($values, $line, $field2column) {
  256. foreach ($values as $field => $value) {
  257. if (is_array($value)) { continue; }
  258. $column = $field2column[$field] - 1;
  259. if ($column < 0) { continue; }
  260. if (preg_match('/\w+/',$line[$column])) {
  261. $values[$field] = $line[$column];
  262. } else {
  263. unset($values[$field]);
  264. }
  265. }
  266. return $values;
  267. }
  268. /**
  269. * Handles foreign keys in the values array.
  270. *
  271. * Specifically, if the value for a field is an array then it is assumed that the array contains
  272. * the name of the record whose values array should be substituted here. Thus the foreign
  273. * record is looked up and the values array is substituted in.
  274. *
  275. */
  276. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  277. foreach ($values as $field => $value) {
  278. if (is_array($value)) {
  279. $foreign_record = $value['foreign record'];
  280. $foreign_priority = $record2priority[$foreign_record];
  281. $foreign_values = $data[$foreign_priority]['values_array'];
  282. // add to current values array
  283. $values[$field] = $foreign_values;
  284. }
  285. }
  286. return $values;
  287. }
  288. /**
  289. * Uses a supplied regex to transform spreadsheet values
  290. *
  291. * @param $values
  292. * The select/insert values array for the given table
  293. * @param $table_data
  294. * The data array for the given table
  295. */
  296. function tripal_bulk_loader_regex_tranform_values ($values, $table_data, $line) {
  297. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) { return $values; }
  298. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  299. if (!is_array($regex_array['replace'])) { continue; }
  300. // Check for <#column:\d+#> notation
  301. // if present replace with that column in the current line
  302. foreach ($regex_array['replace'] as $key => $replace) {
  303. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  304. foreach ($matches[1] as $k => $column_num) {
  305. $replace = preg_replace('/'.$matches[0][$k].'/', $line[$column_num-1], $replace);
  306. }
  307. $regex_array['replace'][$key] = $replace;
  308. }
  309. }
  310. // do the full replacement
  311. $old_value = $values[$field];
  312. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  313. $values[$field] = $new_value;
  314. if ($values[$field] === '') {
  315. unset($values[$field]);
  316. }
  317. }
  318. return $values;
  319. }
  320. /**
  321. * Flattens an array up to two levels
  322. * Used for printing of arrays without taking up much space
  323. */
  324. function tripal_bulk_loader_flatten_array ($values) {
  325. $flattened_values = array();
  326. foreach ($values as $k => $v) {
  327. if (is_array($v)) {
  328. $vstr = array();
  329. foreach ($v as $vk => $vv) {
  330. if (strlen($vv) > 20) {
  331. $vstr[] = $vk .'=>'. substr($vv, 0, 20) . '...';
  332. } else {
  333. $vstr[] = $vk .'=>'. $vv;
  334. }
  335. }
  336. $v = '{'. implode(',',$vstr) .'}';
  337. } elseif (strlen($v) > 20) {
  338. $v = substr($v, 0, 20) . '...';
  339. }
  340. $flattened_values[] = $k .'=>'. $v;
  341. }
  342. return implode(', ',$flattened_values);
  343. }