tripal_bulk_loader.loader.inc 29 KB

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