tripal_bulk_loader.loader.inc 29 KB

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