tripal_bulk_loader.loader.inc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. <?php
  2. /**
  3. * @file
  4. * @todo Add file header description
  5. */
  6. /**
  7. * Add Loader Job Form
  8. *
  9. * This form is meant to be included on the node page to allow users to submit/re-submit
  10. * loading jobs
  11. */
  12. function tripal_bulk_loader_add_loader_job_form($form_state, $node) {
  13. $form = array();
  14. // --notify--
  15. if ($node->job_status == 'Loading...' AND (variable_get('tripal_bulk_loader_transactions', 'row') != 'none')) {
  16. drupal_set_message(t("The Loading Summary only updates at the end of each constant set.
  17. %num records have already been inserted; however, they won't be available until the
  18. current constant set is full loaded and no errors are encountered.", array('%num' => $progress->num_records)), 'warning');
  19. }
  20. $form['nid'] = array(
  21. '#type' => 'hidden',
  22. '#value' => $node->nid,
  23. );
  24. $form['file'] = array(
  25. '#type' => 'hidden',
  26. '#value' => $node->file
  27. );
  28. $form['job_id'] = array(
  29. '#type' => 'hidden',
  30. '#value' => $node->job_id,
  31. );
  32. $form['submit'] = array(
  33. '#type' => 'submit',
  34. '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
  35. );
  36. $form['submit-cancel'] = array(
  37. '#type' => ($node->job_id)? 'submit' : 'hidden',
  38. '#value' => 'Cancel Job',
  39. );
  40. $form['submit-revert'] = array(
  41. '#type' => ($node->job_id) ? 'submit' : 'hidden',
  42. '#value' => 'Revert',
  43. );
  44. return $form;
  45. }
  46. /**
  47. * Add Loader Job Form (Submit)
  48. */
  49. function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
  50. global $user;
  51. if (preg_match('/Submit Job/', $form_state['values']['op'])) {
  52. //Submit Tripal Job
  53. $job_args[1] = $form_state['values']['nid'];
  54. if (is_readable($form_state['values']['file'])) {
  55. $fname = basename($form_state['values']['file']);
  56. $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
  57. // add job_id to bulk_loader node
  58. $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
  59. // change status
  60. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  61. }
  62. else {
  63. drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $form_state['values']['file'])));
  64. }
  65. }
  66. elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
  67. tripal_jobs_rerun($form_state['values']['job_id']);
  68. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  69. }
  70. elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
  71. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Job Cancelled', $form_state['values']['nid']);
  72. tripal_jobs_cancel($form_state['values']['job_id']);
  73. }
  74. elseif (preg_match('/Revert/', $form_state['values']['op'])) {
  75. // Remove the records from the database that were already inserted
  76. $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d ORDER BY tripal_bulk_loader_inserted_id DESC', $form_state['values']['nid']);
  77. while ($r = db_fetch_object($resource)) {
  78. $ids = preg_split('/,/', $r->ids_inserted);
  79. db_query('DELETE FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
  80. $result = db_fetch_object(db_query('SELECT true as present FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted));
  81. if (!$result->present) {
  82. drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', array('%tableto' => $r->table_inserted_into)));
  83. db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d', $r->tripal_bulk_loader_inserted_id);
  84. }
  85. else {
  86. drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', array('%tableto' => $r->table_inserted_into)), 'error');
  87. }
  88. }
  89. // reset status
  90. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Reverted -Data Deleted', $form_state['values']['nid']);
  91. }
  92. }
  93. /**
  94. * Tripal Bulk Loader
  95. *
  96. * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  97. *
  98. * @param $nid
  99. * The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  100. * in the node (ie: template ID and file)
  101. *
  102. * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
  103. * Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
  104. */
  105. function tripal_bulk_loader_load_data($nid, $job_id) {
  106. // ensure no timeout
  107. set_time_limit(0);
  108. // set the status of the job (in the node not the tripal jobs)
  109. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Loading...', $nid);
  110. $node = node_load($nid);
  111. print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
  112. $total_lines = trim(`wc --lines < $node->file`);
  113. print "File: " . $node->file . " (" . $total_lines . " lines)\n";
  114. // Prep Work ==================================================================================
  115. $loaded_without_errors = TRUE;
  116. // Generate default values array
  117. $default_data = array();
  118. $field2column = array();
  119. $record2priority = array();
  120. $tables = array();
  121. foreach ($node->template->template_array as $priority => $record_array) {
  122. if (!is_array($record_array)) {
  123. continue;
  124. }
  125. // Add tables being inserted into to a list to be treated differently
  126. // this is used to acquire locks on these tables
  127. if (preg_match('/insert/', $record_array['mode'])) {
  128. $tables[$record_array['table']] = $record_array['table'];
  129. }
  130. foreach ($record_array['fields'] as $field_index => $field_array) {
  131. $default_data[$priority]['table'] = $record_array['table'];
  132. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
  133. $default_data[$priority]['record_id'] = $record_array['record_id'];
  134. $record2priority[$record_array['record_id']] = $priority;
  135. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  136. $one = $default_data[$priority];
  137. if (isset($field_array['regex'])) {
  138. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  139. }
  140. $two = $default_data[$priority];
  141. if (preg_match('/table field/', $field_array['type'])) {
  142. $default_data[$priority]['values_array'][$field_array['field']] = '';
  143. $default_data[$priority]['need_further_processing'] = TRUE;
  144. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  145. }
  146. elseif (preg_match('/constant/', $field_array['type'])) {
  147. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  148. }
  149. elseif (preg_match('/foreign key/', $field_array['type'])) {
  150. $default_data[$priority]['values_array'][$field_array['field']] = array();
  151. $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
  152. $default_data[$priority]['need_further_processing'] = TRUE;
  153. }
  154. else {
  155. print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
  156. }
  157. $three = $default_data[$priority];
  158. //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);
  159. } // end of foreach field
  160. //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  161. } //end of foreach record
  162. ///////////////////////////////////////////////
  163. // For each set of constants
  164. ///////////////////////////////////////////////
  165. $original_default_data = $default_data;
  166. $group_index = 0;
  167. $total_num_groups = sizeof($node->constants);
  168. foreach ($node->constants as $group_id => $set) {
  169. // revert default data array for next set of constants
  170. $default_data = $original_default_data;
  171. $group_index++;
  172. // Add constants
  173. if (!empty($set)) {
  174. print "Constants:\n";
  175. foreach ($set as $priority => $record) {
  176. foreach ($record as $field_id => $field) {
  177. print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
  178. if ($default_data[$priority]['table'] == $field['chado_table']) {
  179. if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
  180. if (isset($field2column[$priority][$field['chado_field']])) {
  181. $field2column[$priority][$field['chado_field']] = $field['value'];
  182. }
  183. else {
  184. $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
  185. }
  186. }
  187. else {
  188. print "ERROR: Template has changed after constants were assigned!\n";
  189. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  190. exit(1);
  191. }
  192. }
  193. else {
  194. print "ERROR: Template has changed after constants were assigned!\n";
  195. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  196. exit(1);
  197. }
  198. }
  199. }
  200. }
  201. //print "Default Data:".print_r($default_data,TRUE)."\n";
  202. //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  203. //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
  204. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  205. // Parse File adding records as we go ========================================================
  206. // Open File
  207. $file_handle = fopen($node->file, 'r');
  208. // Set defaults
  209. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  210. fgets($file_handle, 4096);
  211. }
  212. $num_records = 0;
  213. $num_lines = 0;
  214. $num_errors = 0;
  215. $interval = intval($total_lines * 0.10);
  216. if ($interval == 0) {
  217. $interval = 1;
  218. }
  219. // Start Transaction
  220. switch (variable_get('tripal_bulk_loader_transactions', 'row')) {
  221. case "none":
  222. break;
  223. case "all":
  224. tripal_db_start_transaction();
  225. $transactions = TRUE;
  226. $savepoint = "";
  227. break;
  228. case "row":
  229. tripal_db_start_transaction();
  230. $transactions = TRUE;
  231. $savepoint = "last_row_complete";
  232. break;
  233. }
  234. // Disable triggers
  235. $triggers_disabled = FALSE;
  236. if ($transactions AND variable_get('tripal_bulk_loader_disable_triggers', TRUE)) {
  237. $triggers_disabled = TRUE;
  238. chado_query("SET CONSTRAINTS ALL DEFERRED");
  239. }
  240. // Acquire Locks
  241. $lockmode = variable_get('tripal_bulk_loader_lock', 'ROW EXCLUSIVE');
  242. foreach ($tables as $table) {
  243. chado_query("LOCK TABLE %s IN %s MODE", $table, $lockmode);
  244. }
  245. tripal_bulk_loader_progress_bar(0,$total_lines);
  246. while (!feof($file_handle)) {
  247. // Clear variables
  248. // Was added to fix memory leak
  249. unset($line); unset($raw_line);
  250. unset($data); unset($data_keys);
  251. unset($priority); unset($sql);
  252. unset($result);
  253. $raw_line = fgets($file_handle, 4096);
  254. $raw_line = trim($raw_line);
  255. if (empty($raw_line)) {
  256. continue;
  257. } // skips blank lines
  258. $line = explode("\t", $raw_line);
  259. $num_lines++;
  260. // update the job status every 10% of lines processed for the current group
  261. if ($node->job_id and $num_lines % $interval == 0) {
  262. // percentage of lines processed for the current group
  263. $group_progress = round(($num_lines/$total_lines)*100);
  264. tripal_bulk_loader_progress_bar($num_lines,$total_lines);
  265. // percentage of lines processed for all groups
  266. // <previous group index> * 100 + <current group progress>
  267. // --------------------------------------------------------
  268. // <total number of groups>
  269. // For example, if you were in the third group of 3 constant sets
  270. // and had a group percentage of 50% then the job progress would be
  271. // (2*100 + 50%) / 3 = 250%/3 = 83%
  272. $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
  273. tripal_job_set_progress($node->job_id, $job_progress);
  274. }
  275. $data = $default_data;
  276. $data_keys = array_keys($data);
  277. foreach ($data_keys as $priority) {
  278. $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
  279. tripal_bulk_loader_progress_file_track_job($job_id, $status);
  280. if (!$status ) {
  281. // Encountered an error
  282. if ($transactions) {
  283. tripal_db_rollback_transaction($savepoint);
  284. }
  285. $failed = TRUE;
  286. break;
  287. }
  288. } // end of foreach table in default data array
  289. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, TRUE);
  290. if ($failed) {
  291. break;
  292. }
  293. else {
  294. // Row inserted successfully
  295. // Set savepoint if supplied
  296. if ($savepoint) {
  297. if ($num_lines == 1) {
  298. tripal_db_set_savepoint_transaction($savepoint);
  299. }
  300. else {
  301. // Tell it to remove the previous savepoint of the same name
  302. tripal_db_set_savepoint_transaction($savepoint, TRUE);
  303. }
  304. }
  305. }
  306. } //end of foreach line of file
  307. // END Transaction
  308. if ($transactions) {
  309. // end the transaction
  310. tripal_db_commit_transaction();
  311. }
  312. if ($failed) {
  313. $loaded_without_errors = FALSE;
  314. break;
  315. }
  316. tripal_bulk_loader_progress_bar($total_lines,$total_lines);
  317. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, FALSE, TRUE);
  318. } //end of foreach constant set
  319. // check that data was inserted and update job_status
  320. $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
  321. $result = db_fetch_object(db_query($sql, $nid));
  322. if ($result->num_tables > 0) {
  323. $node->job_status = 'Data Inserted';
  324. drupal_write_record('node', $node, 'nid');
  325. }
  326. // set the status of the job (in the node not the tripal jobs)
  327. if ($loaded_without_errors) {
  328. $status = 'Loading Completed Successfully';
  329. }
  330. else {
  331. $status = 'Errors Encountered';
  332. }
  333. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
  334. }
  335. /**
  336. *
  337. *
  338. */
  339. function process_data_array_for_line($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
  340. $table_data = $data[$priority];
  341. $no_errors = TRUE;
  342. $table = $table_data['table'];
  343. $values = $table_data['values_array'];
  344. //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  345. //print 'default values:'.print_r($values,TRUE)."\n";
  346. if ($table_data['need_further_processing']) {
  347. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
  348. if (!$values) {
  349. //watchdog('T_bulk_loader', 'Line ' . $line_num . ' Data File Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  350. }
  351. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
  352. if (!$values) {
  353. //watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
  354. }
  355. }
  356. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
  357. if (!$values) {
  358. //watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
  359. }
  360. if (!$values) {
  361. $msg = 'Line ' . $line_num . ' ' . $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);
  362. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  363. print "ERROR: " . $msg . "\n";
  364. $data[$priority]['error'] = TRUE;
  365. $no_errors = FALSE;
  366. }
  367. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  368. if (preg_match('/optional/', $table_array['mode'])) {
  369. // Check all db required fields are set
  370. $fields = $table_desc['fields'];
  371. foreach ($fields as $field => $def) {
  372. // a field is considered missing if it cannot be null and there is no default
  373. // value for it or it is of type 'serial'
  374. if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
  375. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  376. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  377. $data[$priority]['error'] = TRUE;
  378. }
  379. }
  380. } //end of if optional record
  381. // Check required fields are present
  382. foreach ($table_data['required'] as $field => $required) {
  383. if ($required) {
  384. if (!isset($values[$field])) {
  385. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
  386. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  387. $data[$priority]['error'] = TRUE;
  388. }
  389. }
  390. }
  391. // add new values array into the data array
  392. $data[$priority]['values_array'] = $values;
  393. // check if it is already inserted
  394. if ($table_data['inserted']) {
  395. //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
  396. return $no_errors;
  397. }
  398. // if there was an error already -> don't insert
  399. if ($data[$priority]['error']) {
  400. return $no_errors;
  401. }
  402. $header = '';
  403. if (isset($values['feature_id'])) {
  404. $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
  405. }
  406. else {
  407. $header = $values['uniquename'] . ' ' . $table_data['record_id'];
  408. }
  409. // if insert unique then check to ensure unique
  410. if (preg_match('/insert_unique/', $table_data['mode'])) {
  411. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  412. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  413. if ($unique > 0) {
  414. //$default_data[$priority]['inserted'] = TRUE;
  415. //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
  416. return $no_errors;
  417. }
  418. }
  419. if (!preg_match('/select/', $table_data['mode'])) {
  420. // Use prepared statement?
  421. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  422. $options = array('statement_name' => 'record_' . $priority);
  423. if ($line_num == 1 && $group_index == 1) {
  424. $options['prepare'] = TRUE;
  425. }
  426. }
  427. else {
  428. $options = array();
  429. }
  430. // Skip tripal_core_chado_insert() built-in validation?
  431. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  432. $options['skip_validation'] = TRUE;
  433. }
  434. $record = tripal_core_chado_insert($table, $values, $options);
  435. if (!$record) {
  436. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
  437. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  438. print "ERROR: " . $msg . "\n";
  439. $data[$priority]['error'] = TRUE;
  440. $no_errors = FALSE;
  441. }
  442. else {
  443. //add changes back to values array
  444. $data[$priority]['values_array'] = $record;
  445. $values = $record;
  446. // if mode=insert_once then ensure we only insert it once
  447. if (preg_match('/insert_once/', $table_data['mode'])) {
  448. $default_data[$priority]['inserted'] = TRUE;
  449. }
  450. // add to tripal_bulk_loader_inserted
  451. $insert_record = db_fetch_object(db_query(
  452. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  453. $table,
  454. $nid
  455. ));
  456. if ($insert_record) {
  457. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  458. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  459. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  460. return $no_errors;
  461. }
  462. else {
  463. $insert_record = array(
  464. 'nid' => $nid,
  465. 'table_inserted_into' => $table,
  466. 'table_primary_key' => $table_desc['primary key'][0],
  467. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  468. );
  469. //print 'New: '.print_r($insert_record,TRUE)."\n";
  470. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  471. return $no_errors;
  472. }//end of if insert record
  473. } //end of if insert was successful
  474. }
  475. else {
  476. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  477. if (!$exists) {
  478. // No record on select
  479. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  480. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  481. $data[$priority]['error'] = TRUE;
  482. $no_errors = FALSE;
  483. }
  484. }
  485. return $no_errors;
  486. }
  487. /**
  488. * This function adds the file data to the values array
  489. *
  490. * @param $values
  491. * The default values array -contains all constants
  492. * @param $line
  493. * An array of values for the current line
  494. * @param $field2column
  495. * An array mapping values fields to line columns
  496. * @return
  497. * Supplemented values array
  498. */
  499. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  500. foreach ($values as $field => $value) {
  501. if (is_array($value)) {
  502. continue;
  503. }
  504. $column = $field2column[$field] - 1;
  505. if ($column < 0) {
  506. continue;
  507. }
  508. if (preg_match('/\S+/', $line[$column])) {
  509. $values[$field] = $line[$column];
  510. }
  511. else {
  512. unset($values[$field]);
  513. }
  514. }
  515. return $values;
  516. }
  517. /**
  518. * Handles foreign keys in the values array.
  519. *
  520. * Specifically, if the value for a field is an array then it is assumed that the array contains
  521. * the name of the record whose values array should be substituted here. Thus the foreign
  522. * record is looked up and the values array is substituted in.
  523. *
  524. */
  525. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  526. foreach ($values as $field => $value) {
  527. if (is_array($value)) {
  528. $foreign_record = $value['foreign record'];
  529. $foreign_priority = $record2priority[$foreign_record];
  530. $foreign_values = $data[$foreign_priority]['values_array'];
  531. // add to current values array
  532. $values[$field] = $foreign_values;
  533. }
  534. }
  535. return $values;
  536. }
  537. /**
  538. * Uses a supplied regex to transform spreadsheet values
  539. *
  540. * @param $values
  541. * The select/insert values array for the given table
  542. * @param $table_data
  543. * The data array for the given table
  544. */
  545. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  546. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
  547. return $values;
  548. }
  549. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  550. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  551. if (!is_array($regex_array['replace'])) {
  552. continue;
  553. }
  554. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  555. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  556. //print 'Was:'.$values[$field]."\n";
  557. // Check for <#column:\d+#> notation
  558. // if present replace with that column in the current line
  559. foreach ($regex_array['replace'] as $key => $replace) {
  560. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  561. foreach ($matches[1] as $k => $column_num) {
  562. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  563. }
  564. $regex_array['replace'][$key] = $replace;
  565. }
  566. }
  567. // do the full replacement
  568. $old_value = $values[$field];
  569. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  570. $values[$field] = $new_value;
  571. if ($values[$field] === '') {
  572. unset($values[$field]);
  573. }
  574. //print 'Now:'.$values[$field]."\n";
  575. }
  576. return $values;
  577. }
  578. /**
  579. * Flattens an array up to two levels
  580. * Used for printing of arrays without taking up much space
  581. */
  582. function tripal_bulk_loader_flatten_array($values) {
  583. $flattened_values = array();
  584. foreach ($values as $k => $v) {
  585. if (is_array($v)) {
  586. $vstr = array();
  587. foreach ($v as $vk => $vv) {
  588. if (drupal_strlen($vv) > 20) {
  589. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  590. }
  591. else {
  592. $vstr[] = $vk . '=>' . $vv;
  593. }
  594. }
  595. $v = '{' . implode(',', $vstr) . '}';
  596. }
  597. elseif (drupal_strlen($v) > 20) {
  598. $v = drupal_substr($v, 0, 20) . '...';
  599. }
  600. $flattened_values[] = $k . '=>' . $v;
  601. }
  602. return implode(', ', $flattened_values);
  603. }
  604. /**
  605. * Used to display loader progress to the user
  606. */
  607. function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
  608. // First iteration
  609. if($current == 0) {
  610. $new_bar = TRUE;
  611. fputs(STDOUT,"Progress:\n");
  612. }
  613. //Percentage round off for a more clean, consistent look
  614. $perc = round(($current/$total)*100,2);
  615. // percent indicator must be four characters, if shorter, add some spaces
  616. for($i=strlen($perc); $i<=4; $i++) {
  617. $perc = ' '.$perc;
  618. }
  619. $total_size = $size + $i + 3 + 2;
  620. // if it's not first go, remove the previous bar
  621. if(!$new_bar) {
  622. for($place = $total_size; $place > 0; $place--) {
  623. // echo a backspace (hex:08) to remove the previous character
  624. echo "\x08";
  625. }
  626. }
  627. // output the progess bar as it should be
  628. // Start with a border
  629. echo '[';
  630. for($place = 0; $place <= $size; $place++) {
  631. // output "full" spaces if this portion is completed
  632. if($place <= ($current / $total * $size)) {
  633. echo '|';
  634. }
  635. else {
  636. // Otherwise empty space
  637. echo '-';
  638. }
  639. }
  640. // End with a border
  641. echo ']';
  642. // end a bar with a percent indicator
  643. echo " $perc%";
  644. // if it's the end, add a new line
  645. if($current == $total) {
  646. echo "\n";
  647. }
  648. }
  649. /**
  650. * Keep track of progress in file rather then database
  651. *
  652. * This provides an alternative method to keep track of progress that doesn't require the
  653. * database. It was needed because you can't switch databases within a transaction...
  654. * Waiting until the end of a constant set is much too long to wait for any indication
  655. * that things are working.
  656. *
  657. * Each line represents a line processed in the loading file. Each period (.) represents
  658. * a successfully inserted record.
  659. *
  660. * @param $job_id
  661. * The ID of the current tripal job
  662. * @param $record_added
  663. * A boolean indicated whether a record was added successfully
  664. * @param $line_complete
  665. * A boolean indicating whether the current line is finished
  666. * @param $close
  667. * A boolean indicating that the file should be closed
  668. */
  669. function tripal_bulk_loader_progress_file_track_job($job_id, $record_added, $line_complete = FALSE, $close = FALSE) {
  670. // retrieve the file handle
  671. $file_handle = variable_get('tripal_bulk_loader_progress_file_handle',NULL);
  672. // open file for reading if not already
  673. if (!$file_handle) {
  674. $file_handle = fopen('/tmp/tripal_bulk_loader_progress-'.$job_id.'.out', 'w');
  675. variable_set('tripal_bulk_loader_progress_file_handle', $file_handle);
  676. }
  677. if ($record_added) {
  678. fwrite($file_handle,'.');
  679. }
  680. if ($line_complete) {
  681. fwrite($file_handle,"\n");
  682. }
  683. // close the file if finished
  684. if ($close) {
  685. fclose($file_handle);
  686. variable_set('tripal_bulk_loader_progress_file_handle', NULL);
  687. }
  688. }