tripal_bulk_loader.loader.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. // change status
  50. db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Submitted to Queue', $form_state['values']['nid']);
  51. } else {
  52. drupal_set_message("Can not open ".$form_state['values']['file'].". Job not scheduled.");
  53. }
  54. } elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
  55. tripal_jobs_rerun($form_state['values']['job_id']);
  56. db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Submitted to Queue', $form_state['values']['nid']);
  57. } elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
  58. db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Job Cancelled', $form_state['values']['nid']);
  59. tripal_jobs_cancel($form_state['values']['job_id']);
  60. } elseif (preg_match('/Revert/', $form_state['values']['op'])) {
  61. // Remove the records from the database that were already inserted
  62. $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d', $form_state['values']['nid']);
  63. while ($r = db_fetch_object($resource)) {
  64. $ids = preg_split('/,/',$r->ids_inserted);
  65. db_query('DELETE FROM %s WHERE %s IN (%s)',$r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
  66. db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d',$r->tripal_bulk_loader_inserted_id);
  67. }
  68. // reset status
  69. db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Reverted -Data Deleted', $form_state['values']['nid']);
  70. }
  71. }
  72. /**
  73. * Tripal Bulk Loader
  74. *
  75. * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  76. *
  77. * @param $nid
  78. * The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  79. * in the node (ie: template ID and file)
  80. *
  81. * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
  82. * Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
  83. */
  84. function tripal_bulk_loader_load_data($nid) {
  85. // ensure no timeout
  86. set_time_limit(0);
  87. // set the status of the job (in the node not the tripal jobs)
  88. db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",'Loading...', $nid);
  89. print "Memory Usage (Start): ".number_format((memory_get_usage() * 0.000000953674316), 5, '.', ',') . " Mb\n";
  90. $node = node_load($nid);
  91. print "Template: ".$node->template->name." (".$node->template_id.")\n";
  92. print "File: ".$node->file."\n";
  93. print "Memory Usage (After Node Load): ".number_format((memory_get_usage() * 0.000000953674316), 5, '.', ',') . " Mb\n";
  94. // Prep Work ==================================================================================
  95. $loaded_without_errors = TRUE;
  96. // Generate default values array
  97. $default_data = array();
  98. $field2column = array();
  99. $record2priority = array();
  100. foreach ($node->template->template_array as $priority => $record_array) {
  101. if (!is_array($record_array)) { continue; }
  102. //watchdog('T_bulk_loader','1)'.$record_array['record_id']." => \n<pre>".print_r($record_array,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  103. foreach ($record_array['fields'] as $field_index => $field_array) {
  104. $default_data[$priority]['table'] = $record_array['table'];
  105. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
  106. $default_data[$priority]['record_id'] = $record_array['record_id'];
  107. $record2priority[$record_array['record_id']] = $priority;
  108. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  109. $one = $default_data[$priority];
  110. if (isset($field_array['regex'])) {
  111. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  112. }
  113. $two = $default_data[$priority];
  114. if (preg_match('/table field/', $field_array['type'])) {
  115. $default_data[$priority]['values_array'][$field_array['field']] = '';
  116. $default_data[$priority]['need_further_processing'] = TRUE;
  117. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  118. } elseif (preg_match('/constant/', $field_array['type'])) {
  119. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  120. } elseif (preg_match('/foreign key/', $field_array['type'])) {
  121. $default_data[$priority]['values_array'][$field_array['field']] = array();
  122. $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
  123. $default_data[$priority]['need_further_processing'] = TRUE;
  124. } else {
  125. print 'WARNING: Unsupported type: '. $field_array['type'] . ' for ' . $table . '.' . $field_array['field']."!\n";
  126. }
  127. $three = $default_data[$priority];
  128. //watchdog('T_bulk_loader','A)'.$field_index.':<pre>Field Array =>'.print_r($field_array,TRUE)."Initial => \n".print_r($one, TRUE)."\nAfter Regex =>".print_r($two, TRUE)."Final =>\n".print_r($three,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  129. } // end of foreach field
  130. //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  131. } //end of foreach record
  132. print "Memory Usage (end of prep work): ".number_format((memory_get_usage() * 0.000000953674316), 5, '.', ',') . " Mb\n";
  133. //print "Default Data:".print_r($default_data,TRUE)."\n";
  134. //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  135. //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
  136. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  137. // Parse File adding records as we go ========================================================
  138. $file_handle = fopen($node->file, 'r');
  139. if (preg_match('/(t|true|1)/', $node->file_has_header)) { fgets($file_handle, 4096); }
  140. $num_records = 0;
  141. $num_lines = 0;
  142. $num_errors = 0;
  143. while (!feof($file_handle)) {
  144. // Clear variables
  145. // Was added to fix memory leak
  146. unset($line); unset($raw_line);
  147. unset($data); unset($data_keys);
  148. unset($priority); unset($sql);
  149. unset($result);
  150. $raw_line = fgets($file_handle, 4096);
  151. $raw_line = trim($raw_line);
  152. if (empty($raw_line)) { continue; } // skips blank lines
  153. $line = explode("\t", $raw_line);
  154. $num_lines++;
  155. $data = $default_data;
  156. $data_keys = array_keys($data);
  157. foreach ($data_keys as $priority) {
  158. $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid);
  159. if (!$status ) { $loaded_without_errors = FALSE; }
  160. } // end of foreach table in default data array
  161. // determine memory increase
  162. $line_mem_increase = memory_get_usage() - $memory;
  163. if ($num_lines != 1) {
  164. $increased_mem = $increased_mem + $line_mem_increase;
  165. }
  166. $memory = memory_get_usage();
  167. } //end of foreach line of file
  168. // check that data was inserted and update job_status
  169. $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
  170. $result = db_fetch_object(db_query($sql, $nid));
  171. if ($result->num_tables > 0) {
  172. $node->job_status = 'Data Inserted';
  173. drupal_write_record('node',$node,'nid');
  174. }
  175. // set the status of the job (in the node not the tripal jobs)
  176. if ($loaded_without_errors) { $status = 'Loading Completed Successfully'; } else { $status = 'Errors Encountered'; }
  177. db_query("UPDATE tripal_bulk_loader SET job_status='%s' WHERE nid=%d",$status, $nid);
  178. $avg_line_increase = ( $increased_mem / $num_lines) * 0.0078125;
  179. print "Average Increase in Memory per Line: ".number_format($avg_line_increase, 5, '.', ',') . " Kb\n";
  180. print "Peak Memory Usage: ".number_format((memory_get_peak_usage() * 0.000000953674316), 5, '.', ',') . " Mb\n";
  181. print "End Memory Usage: ".number_format((memory_get_usage() * 0.000000953674316), 5, '.', ',') . " Mb\n";
  182. }
  183. /**
  184. *
  185. *
  186. */
  187. function process_data_array_for_line ($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid) {
  188. $table_data = $data[$priority];
  189. $no_errors = TRUE;
  190. $table = $table_data['table'];
  191. $values = $table_data['values_array'];
  192. //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  193. //print 'default values:'.print_r($values,TRUE)."\n";
  194. if ($table_data['need_further_processing']) {
  195. $values = tripal_bulk_loader_add_spreadsheetdata_to_values ($values, $line, $field2column[$priority]);
  196. if (!$values) {
  197. watchdog('T_bulk_loader','Spreadsheet Added:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  198. }
  199. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
  200. if (!$values) {
  201. watchdog('T_bulk_loader','FK Added:<pre>'.print_r($values, TRUE).print_r($data[$priority],TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  202. }
  203. }
  204. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
  205. if (!$values) {
  206. watchdog('T_bulk_loader','Regex:<pre>'.print_r($values, TRUE).print_r($table_data, TRUE).'</pre>'.'</pre>', array(), WATCHDOG_NOTICE);
  207. }
  208. if (!$values) {
  209. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Aborted due to error in previous record. Values of current record:'.print_r($table_data['values_array'],TRUE);
  210. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  211. print "ERROR: ".$msg."\n";
  212. $data[$priority]['error'] = TRUE;
  213. $no_errors = FALSE;
  214. }
  215. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  216. if (preg_match('/optional/', $table_array['mode'])) {
  217. // Check all db required fields are set
  218. $fields = $table_desc['fields'];
  219. foreach($fields as $field => $def){
  220. // a field is considered missing if it cannot be null and there is no default
  221. // value for it or it is of type 'serial'
  222. if($def['not null'] == 1 and !array_key_exists($field,$insert_values) and !isset($def['default']) and strcmp($def['type'],serial)!=0){
  223. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Missing Database Required Value: '.$table.'.'.$field;
  224. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  225. $data[$priority]['error'] = TRUE;
  226. }
  227. }
  228. } //end of if optional record
  229. // Check required fields are present
  230. foreach ($table_data['required'] as $field => $required) {
  231. if ($required) {
  232. if (!isset($values[$field])) {
  233. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Missing Template Required Value: '.$table.'.'.$field;
  234. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  235. $data[$priority]['error'] = TRUE;
  236. }
  237. }
  238. }
  239. // add new values array into the data array
  240. $data[$priority]['values_array'] = $values;
  241. // check if it is already inserted
  242. if ($table_data['inserted']) {
  243. //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
  244. return $no_errors;
  245. }
  246. // if there was an error already -> don't insert
  247. if ($data[$priority]['error']) {
  248. return $no_errors;
  249. }
  250. $header = '';
  251. if (isset($values['feature_id'])) {
  252. $header = $values['feature_id']['uniquename'] .' '. $table_data['record_id'];
  253. } else {
  254. $header = $values['uniquename'] .' '. $table_data['record_id'];
  255. }
  256. // if insert unique then check to ensure unique
  257. if (preg_match('/insert_unique/',$table_data['mode'])) {
  258. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record'=>TRUE));
  259. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  260. if ($unique > 0) {
  261. //$default_data[$priority]['inserted'] = TRUE;
  262. //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
  263. return $no_errors;
  264. }
  265. }
  266. if (!preg_match('/select/',$table_data['mode'])) {
  267. //watchdog('T_bulk_loader',$header.': Inserting:'.print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  268. $record = tripal_core_chado_insert($table, $values);
  269. if (!$record) {
  270. $msg = $table_data['record_id'].' ('.$table_data['mode'].') Unable to insert record into '.$table.' where values:'.print_r($values,TRUE);
  271. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  272. print "ERROR: ".$msg."\n";
  273. $data[$priority]['error'] = TRUE;
  274. $no_errors = FALSE;
  275. } else {
  276. //add changes back to values array
  277. $data[$priority]['values_array'] = $record;
  278. $values = $record;
  279. // if mode=insert_once then ensure we only insert it once
  280. if (preg_match('/insert_once/',$table_data['mode'])) {
  281. $default_data[$priority]['inserted'] = TRUE;
  282. }
  283. // add to tripal_bulk_loader_inserted
  284. $insert_record = db_fetch_object(db_query(
  285. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  286. $table,
  287. $nid
  288. ));
  289. if ($insert_record) {
  290. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  291. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  292. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  293. return $no_errors;
  294. } else {
  295. $insert_record = array(
  296. 'nid' => $nid,
  297. 'table_inserted_into' => $table,
  298. 'table_primary_key' => $table_desc['primary key'][0],
  299. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  300. );
  301. //print 'New: '.print_r($insert_record,TRUE)."\n";
  302. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  303. return $no_errors;
  304. }//end of if insert record
  305. } //end of if insert was successful
  306. } else {
  307. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record'=>TRUE));
  308. if (!$exists) {
  309. // No record on select
  310. $msg = $table_data['record_id'].' ('.$table_data['mode'].') No Matching record in '.$table.' where values:'.print_r($values,TRUE);
  311. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  312. $data[$priority]['error'] = TRUE;
  313. }
  314. }
  315. return $no_errors;
  316. }
  317. /**
  318. * This function adds the file data to the values array
  319. *
  320. * @param $values
  321. * The default values array -contains all constants
  322. * @param $line
  323. * An array of values for the current line
  324. * @param $field2column
  325. * An array mapping values fields to line columns
  326. * @return
  327. * Supplemented values array
  328. */
  329. function tripal_bulk_loader_add_spreadsheetdata_to_values ($values, $line, $field2column) {
  330. foreach ($values as $field => $value) {
  331. if (is_array($value)) { continue; }
  332. $column = $field2column[$field] - 1;
  333. if ($column < 0) { continue; }
  334. if (preg_match('/\S+/',$line[$column])) {
  335. $values[$field] = $line[$column];
  336. } else {
  337. unset($values[$field]);
  338. }
  339. }
  340. return $values;
  341. }
  342. /**
  343. * Handles foreign keys in the values array.
  344. *
  345. * Specifically, if the value for a field is an array then it is assumed that the array contains
  346. * the name of the record whose values array should be substituted here. Thus the foreign
  347. * record is looked up and the values array is substituted in.
  348. *
  349. */
  350. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  351. foreach ($values as $field => $value) {
  352. if (is_array($value)) {
  353. $foreign_record = $value['foreign record'];
  354. $foreign_priority = $record2priority[$foreign_record];
  355. $foreign_values = $data[$foreign_priority]['values_array'];
  356. // add to current values array
  357. $values[$field] = $foreign_values;
  358. }
  359. }
  360. return $values;
  361. }
  362. /**
  363. * Uses a supplied regex to transform spreadsheet values
  364. *
  365. * @param $values
  366. * The select/insert values array for the given table
  367. * @param $table_data
  368. * The data array for the given table
  369. */
  370. function tripal_bulk_loader_regex_tranform_values ($values, $table_data, $line) {
  371. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) { return $values; }
  372. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  373. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  374. if (!is_array($regex_array['replace'])) { continue; }
  375. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  376. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  377. //print 'Was:'.$values[$field]."\n";
  378. // Check for <#column:\d+#> notation
  379. // if present replace with that column in the current line
  380. foreach ($regex_array['replace'] as $key => $replace) {
  381. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  382. foreach ($matches[1] as $k => $column_num) {
  383. $replace = preg_replace('/'.$matches[0][$k].'/', $line[$column_num-1], $replace);
  384. }
  385. $regex_array['replace'][$key] = $replace;
  386. }
  387. }
  388. // do the full replacement
  389. $old_value = $values[$field];
  390. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  391. $values[$field] = $new_value;
  392. if ($values[$field] === '') {
  393. unset($values[$field]);
  394. }
  395. //print 'Now:'.$values[$field]."\n";
  396. }
  397. return $values;
  398. }
  399. /**
  400. * Flattens an array up to two levels
  401. * Used for printing of arrays without taking up much space
  402. */
  403. function tripal_bulk_loader_flatten_array ($values) {
  404. $flattened_values = array();
  405. foreach ($values as $k => $v) {
  406. if (is_array($v)) {
  407. $vstr = array();
  408. foreach ($v as $vk => $vv) {
  409. if (strlen($vv) > 20) {
  410. $vstr[] = $vk .'=>'. substr($vv, 0, 20) . '...';
  411. } else {
  412. $vstr[] = $vk .'=>'. $vv;
  413. }
  414. }
  415. $v = '{'. implode(',',$vstr) .'}';
  416. } elseif (strlen($v) > 20) {
  417. $v = substr($v, 0, 20) . '...';
  418. }
  419. $flattened_values[] = $k .'=>'. $v;
  420. }
  421. return implode(', ',$flattened_values);
  422. }