tripal_bulk_loader.loader.inc 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. <?php
  2. /**
  3. * @file
  4. * Handles the actual loading of data.
  5. *
  6. * @ingroup tripal_bulk_loader
  7. */
  8. /**
  9. * Add Loader Job Form
  10. *
  11. * This form is meant to be included on the node page to allow users to
  12. * submit/re-submit loading jobs
  13. *
  14. * @ingroup tripal_bulk_loader
  15. */
  16. function tripal_bulk_loader_add_loader_job_form($form, &$form_state, $node) {
  17. $form = [];
  18. // --notify--
  19. if ($node->job_status == 'Loading...') {
  20. drupal_set_message(t("The Loading Summary only updates at the end of each constant set.
  21. Although records may have already been inserted, they won't be available until the
  22. current constant set is full loaded and no errors are encountered.", []), 'warning');
  23. }
  24. $form['nid'] = [
  25. '#type' => 'hidden',
  26. '#value' => $node->nid,
  27. ];
  28. $form['file'] = [
  29. '#type' => 'hidden',
  30. '#value' => $node->file,
  31. ];
  32. $form['job_id'] = [
  33. '#type' => 'hidden',
  34. '#value' => $node->job_id,
  35. ];
  36. $form['submit'] = [
  37. '#type' => 'submit',
  38. '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
  39. ];
  40. $form['submit-cancel'] = [
  41. '#type' => ($node->job_id) ? 'submit' : 'hidden',
  42. '#value' => 'Cancel Job',
  43. ];
  44. if ($node->keep_track_inserted) {
  45. $form['submit-revert'] = [
  46. '#type' => ($node->job_id) ? 'submit' : 'hidden',
  47. '#value' => 'Revert',
  48. ];
  49. }
  50. return $form;
  51. }
  52. /**
  53. * Add Loader Job Form (Submit)
  54. *
  55. * @ingroup tripal_bulk_loader
  56. */
  57. function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
  58. global $user;
  59. if (preg_match('/Submit Job/', $form_state['values']['op'])) {
  60. //Submit Tripal Job
  61. $job_args[1] = $form_state['values']['nid'];
  62. if (is_readable($form_state['values']['file'])) {
  63. $fname = basename($form_state['values']['file']);
  64. $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
  65. // add job_id to bulk_loader node
  66. $success = db_update('tripal_bulk_loader')->fields([
  67. 'job_id' => $job_id,
  68. 'job_status' => 'Submitted to Queue',
  69. ])->condition('nid', $form_state['values']['nid'])->execute();
  70. }
  71. else {
  72. drupal_set_message(t("Can not open %file. Job not scheduled.", ['%file' => $form_state['values']['file']]));
  73. }
  74. }
  75. elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
  76. tripal_rerun_job($form_state['values']['job_id']);
  77. $success = db_update('tripal_bulk_loader')->fields([
  78. 'job_status' => 'Submitted to Queue',
  79. ])->condition('nid', $form_state['values']['nid'])->execute();
  80. }
  81. elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
  82. $success = db_update('tripal_bulk_loader')->fields([
  83. 'job_status' => 'Job Cancelled',
  84. ])->condition('nid', $form_state['values']['nid'])->execute();
  85. tripal_cancel_job($form_state['values']['job_id']);
  86. }
  87. elseif (preg_match('/Revert/', $form_state['values']['op'])) {
  88. // Remove the records from the database that were already inserted
  89. $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=:nid ORDER BY tripal_bulk_loader_inserted_id DESC', [':nid' => $form_state['values']['nid']]);
  90. while ($r = $resource->fetchObject()) {
  91. $ids = preg_split('/,/', $r->ids_inserted);
  92. db_query('DELETE FROM {' . $r->table_inserted_into . '} WHERE ' . $r->table_primary_key . ' IN (' . $r->ids_inserted . ')')->execute();
  93. $result = db_query('SELECT true as present FROM {' . $r->table_inserted_into . '} WHERE ' . $r->table_primary_key . ' IN (' . $r->ids_inserted . ')')->fetchObject();
  94. if (!$result->present) {
  95. drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', ['%tableto' => $r->table_inserted_into]));
  96. db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=:id', [':id' => $r->tripal_bulk_loader_inserted_id])->execute();
  97. }
  98. else {
  99. drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', ['%tableto' => $r->table_inserted_into]), 'error');
  100. }
  101. }
  102. // reset status
  103. $success = db_update('tripal_bulk_loader')->fields([
  104. 'job_status' => 'Reverted -Data Deleted',
  105. ])->condition('nid', $form_state['values']['nid'])->execute();
  106. }
  107. }
  108. /**
  109. * Tripal Bulk Loader
  110. *
  111. * This is the function that's run by tripal_launch_jobs to bulk load chado
  112. * data.
  113. *
  114. * @param $nid
  115. * The Node ID of the bulk loading job node to be loaded. All other needed
  116. * data is expected to be in the node (ie: template ID and file)
  117. *
  118. * Note: Instead of returning a value this function updates the
  119. * tripal_bulk_loader.status. Errors are thrown through watchdog and can be
  120. * viewed at admin/reports/dblog.
  121. *
  122. * @ingroup tripal_bulk_loader
  123. */
  124. function tripal_bulk_loader_load_data($nid, $job_id) {
  125. // ensure no timeout
  126. drupal_set_time_limit(0);
  127. // set the status of the job (in the node not the tripal jobs)
  128. db_update('tripal_bulk_loader')
  129. ->fields(['job_status' => 'Loading...'])
  130. ->condition('nid', $nid)
  131. ->execute();
  132. $node = node_load($nid);
  133. print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
  134. // Determine the total number of non-blank lines in the file.
  135. $total_lines = 0;
  136. $handle = fopen($node->file, "r");
  137. while (!feof($handle)) {
  138. $line = fgets($handle);
  139. $line = trim($line);
  140. if (empty($line)) {
  141. continue;
  142. } // skips blank lines
  143. $total_lines++;
  144. }
  145. fclose($handle);
  146. // Correct for files with a single line and no enter character.
  147. $total_lines = ($total_lines == 0) ? 1 : $total_lines;
  148. print "File: " . $node->file . " (" . $total_lines . " lines)\n";
  149. //print "\nClearing all prepared statements from previous runs of this loader...\n";
  150. //tripal_core_chado_clear_prepared('_'.$node->nid.'_');
  151. // Prep Work ==================================================================================
  152. print "\nPreparing to load...\n";
  153. $loaded_without_errors = TRUE;
  154. // Generate default values array
  155. $default_data = [];
  156. $field2column = [];
  157. $record2priority = [];
  158. $tables = [];
  159. $template_array = $node->template->template_array;
  160. // first build the record2priority array
  161. foreach ($template_array as $priority => $record_array) {
  162. $record2priority[$record_array['record_id']] = $priority;
  163. }
  164. //
  165. foreach ($template_array as $priority => $record_array) {
  166. if (!is_array($record_array)) {
  167. continue;
  168. }
  169. // Add tables being inserted into to a list to be treated differently
  170. // this is used to acquire locks on these tables
  171. if (preg_match('/insert/', $record_array['mode'])) {
  172. $tables[$record_array['table']] = $record_array['table'];
  173. }
  174. // iterate through each of the fields for the current record and
  175. // set the default_data array
  176. foreach ($record_array['fields'] as $field_index => $field_array) {
  177. $default_data[$priority]['table'] = $record_array['table'];
  178. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert';
  179. $default_data[$priority]['select_if_duplicate'] = ($record_array['select_if_duplicate']) ? $record_array['select_if_duplicate'] : 0;
  180. $default_data[$priority]['update_if_duplicate'] = ($record_array['update_if_duplicate']) ? $record_array['update_if_duplicate'] : 0;
  181. $default_data[$priority]['disabled'] = ($record_array['disable']) ? $record_array['disable'] : 0;
  182. $default_data[$priority]['optional'] = ($record_array['optional']) ? $record_array['optional'] : 0;
  183. $default_data[$priority]['select_optional'] = ($record_array['select_optional']) ? $record_array['select_optional'] : 0;
  184. $default_data[$priority]['record_id'] = $record_array['record_id'];
  185. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  186. $one = $default_data[$priority];
  187. if (isset($field_array['regex'])) {
  188. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  189. }
  190. $two = $default_data[$priority];
  191. if (preg_match('/table field/', $field_array['type'])) {
  192. $default_data[$priority]['values_array'][$field_array['field']] = '';
  193. $default_data[$priority]['need_further_processing'] = TRUE;
  194. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  195. }
  196. elseif (preg_match('/constant/', $field_array['type'])) {
  197. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  198. }
  199. elseif (preg_match('/foreign key/', $field_array['type'])) {
  200. $default_data[$priority]['values_array'][$field_array['field']] = [];
  201. $default_data[$priority]['need_further_processing'] = TRUE;
  202. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['record'] = $field_array['foreign key'];
  203. // Add in the FK / Referral table
  204. $fk_priority = $record2priority[$field_array['foreign key']];
  205. $fk_table = $template_array[$fk_priority]['table'];
  206. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['table'] = $fk_table;
  207. // Add in the FK / Referral field
  208. // for backwards compatibility we need to get the FK relationship to find
  209. // out what field we're joining on. For templates created using a
  210. // previous version it was assumed that the FK field was always the field to join
  211. if (!array_key_exists('foreign field', $field_array)) {
  212. $tbl_description = chado_get_schema($record_array['table']);
  213. foreach ($tbl_description['foreign keys'] as $key_table => $key_array) {
  214. if ($key_table == $fk_table) {
  215. foreach ($key_array['columns'] as $left_field => $right_field) {
  216. if ($left_field == $field_array['field']) {
  217. $field_array['foreign field'] = $right_field;
  218. }
  219. }
  220. }
  221. }
  222. }
  223. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['field'] = $field_array['foreign field'];
  224. }
  225. else {
  226. print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
  227. }
  228. $three = $default_data[$priority];
  229. } // end of foreach field
  230. } //end of foreach record
  231. ///////////////////////////////////////////////
  232. // For each set of constants
  233. ///////////////////////////////////////////////
  234. print "Loading...\n";
  235. $original_default_data = $default_data;
  236. $group_index = 0;
  237. $total_num_groups = sizeof($node->constants);
  238. // If there are no constant sets and no exposed fields
  239. // then create an empty constant set so loader runs
  240. if ($total_num_groups == 0 && empty($node->exposed_fields)) {
  241. $node->constants = [
  242. 0 => [],
  243. ];
  244. $total_num_groups = 1;
  245. }
  246. foreach ($node->constants as $group_id => $set) {
  247. // revert default data array for next set of constants
  248. $default_data = $original_default_data;
  249. $group_index++;
  250. // Add constants
  251. if (!empty($set)) {
  252. print "Constants:\n";
  253. foreach ($set as $priority => $record) {
  254. foreach ($record as $field_id => $field) {
  255. print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
  256. if ($default_data[$priority]['table'] == $field['chado_table']) {
  257. if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
  258. if (isset($field2column[$priority][$field['chado_field']])) {
  259. $field2column[$priority][$field['chado_field']] = $field['value'];
  260. }
  261. else {
  262. $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
  263. }
  264. }
  265. else {
  266. print "ERROR: Template has changed after constants were assigned!\n";
  267. tripal_bulk_loader_throw_error('Template has changed after constants were assigned', [], TRIPAL_NOTICE);
  268. exit(1);
  269. }
  270. }
  271. else {
  272. print "ERROR: Template has changed after constants were assigned!\n";
  273. tripal_bulk_loader_throw_error('Template has changed after constants were assigned', [], TRIPAL_NOTICE);
  274. exit(1);
  275. }
  276. }
  277. }
  278. }
  279. // Open File
  280. print "\tPreparing to load the current constant set...\n";
  281. print "\t\tOpen File...\n";
  282. try {
  283. $file = new SplFileObject($node->file, 'r');
  284. } catch (Exception $e) {
  285. tripal_bulk_loader_throw_error('Could not open file %file',
  286. ['%file' => $node->file], TRIPAL_ERROR);
  287. return;
  288. }
  289. // Set defaults
  290. $header = '';
  291. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  292. $file->next();
  293. $header = $file->current();
  294. }
  295. $num_records = 0;
  296. $num_lines = 0;
  297. $num_errors = 0;
  298. $interval = intval($total_lines * 0.0001);
  299. if ($interval == 0) {
  300. $interval = 1;
  301. }
  302. // Start Transaction
  303. $savepoint = '';
  304. switch (variable_get('tripal_bulk_loader_transactions', 'row')) {
  305. case "none":
  306. break;
  307. case "all":
  308. print "\t\tStart Transaction...\n";
  309. $TRANSACTION = db_transaction();
  310. $transactions = TRUE;
  311. break;
  312. case "row":
  313. print "\t\tStart Transaction...\n";
  314. $TRANSACTION = db_transaction();
  315. $transactions = TRUE;
  316. $new_transaction_per_row = TRUE;
  317. break;
  318. }
  319. // Disable triggers
  320. $triggers_disabled = FALSE;
  321. if ($transactions AND variable_get('tripal_bulk_loader_disable_triggers', TRUE)) {
  322. print "\t\tDefer Constraints...\n";
  323. $triggers_disabled = TRUE;
  324. chado_query("SET CONSTRAINTS ALL DEFERRED");
  325. }
  326. // Acquire Locks
  327. if ($transactions) {
  328. print "\t\tAcquiring Table Locks...\n";
  329. $lockmode = variable_get('tripal_bulk_loader_lock', 'ROW EXCLUSIVE');
  330. foreach ($tables as $table) {
  331. print "\t\t\t$lockmode for $table\n";
  332. chado_query("LOCK TABLE {" . $table . "} IN " . $lockmode . " MODE");
  333. }
  334. }
  335. print "\tLoading the current constant set...\n";
  336. tripal_bulk_loader_progress_bar(0, $total_lines);
  337. while (!$file->eof()) {
  338. $file->next();
  339. $raw_line = $file->current();
  340. $raw_line = trim($raw_line);
  341. if (empty($raw_line)) {
  342. continue;
  343. } // skips blank lines
  344. $line = explode("\t", $raw_line);
  345. $num_lines++;
  346. // update the job status every 1% of lines processed for the current group
  347. if ($node->job_id and $num_lines % $interval == 0) {
  348. // percentage of lines processed for the current group
  349. $group_progress = round(($num_lines / $total_lines) * 100);
  350. tripal_bulk_loader_progress_bar($num_lines, $total_lines);
  351. // percentage of lines processed for all groups
  352. // <previous group index> * 100 + <current group progress>
  353. // --------------------------------------------------------
  354. // <total number of groups>
  355. // For example, if you were in the third group of 3 constant sets
  356. // and had a group percentage of 50% then the job progress would be
  357. // (2*100 + 50%) / 3 = 250%/3 = 83%
  358. $job_progress = round(((($group_index - 1) * 100) + $group_progress) / $total_num_groups);
  359. tripal_set_job_progress($node->job_id, $job_progress);
  360. }
  361. $data = $default_data;
  362. // iterate through each record and process the line
  363. $data_keys = array_keys($data);
  364. foreach ($data_keys as $priority) {
  365. $options = [
  366. 'field2column' => $field2column,
  367. 'record2priority' => $record2priority,
  368. 'line' => $line,
  369. 'line_num' => $num_lines,
  370. 'group_index' => $group_index,
  371. 'node' => $node,
  372. 'nid' => $node->nid,
  373. ];
  374. // execute all records that are not disabled
  375. $no_errors = FALSE;
  376. if (array_key_exists($priority, $data) and
  377. array_key_exists('disabled', $data[$priority]) and
  378. $data[$priority]['disabled'] == 0) {
  379. $no_errors = process_data_array_for_line($priority, $data, $default_data, $options);
  380. }
  381. else {
  382. // set status to true for skipped records
  383. $no_errors = TRUE;
  384. }
  385. tripal_bulk_loader_progress_file_track_job($job_id, $no_errors);
  386. $failed = FALSE;
  387. if ($no_errors == FALSE) {
  388. // Encountered an error
  389. if ($transactions) {
  390. $TRANSACTION->rollback();
  391. }
  392. tripal_bulk_loader_finish_loading($node->nid, FALSE);
  393. break;
  394. }
  395. } // end of foreach table in default data array
  396. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, TRUE);
  397. if ($failed) {
  398. $TRANSACTION->rollback();
  399. tripal_bulk_loader_finish_loading($node->nid, FALSE);
  400. break;
  401. }
  402. else {
  403. // Row inserted successfully
  404. if ($transactions && $new_transaction_per_row) {
  405. // commit current transaction and start a new one
  406. unset($TRANSACTION);
  407. $TRANSACTION = db_transaction();
  408. }
  409. }
  410. } //end of foreach line of file
  411. // END Transaction
  412. if ($transactions) {
  413. unset($TRANSACTION);
  414. }
  415. if ($failed) {
  416. $loaded_without_errors = FALSE;
  417. break;
  418. }
  419. tripal_bulk_loader_progress_bar($total_lines, $total_lines);
  420. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, FALSE, TRUE);
  421. } //end of foreach constant set
  422. tripal_bulk_loader_finish_loading($node->nid, $loaded_without_errors);
  423. }
  424. /**
  425. * Process the data array for a given line
  426. *
  427. * @param $addt
  428. * Requires: field2column', 'record2priority', 'line', 'line_num',
  429. * 'group_index', 'node', 'nid'
  430. *
  431. * @ingroup tripal_bulk_loader
  432. */
  433. function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
  434. //$time_start = microtime(true);
  435. $table_data = $data[$priority];
  436. $addt = (object) $addt;
  437. $no_errors = TRUE;
  438. $table = $table_data['table'];
  439. $values = $table_data['values_array'];
  440. // populate the values array with real value either from the input data file line
  441. // or from the foreign key / referral record
  442. if (array_key_exists('need_further_processing', $table_data) and $table_data['need_further_processing']) {
  443. if (array_key_exists($priority, $addt->field2column)) {
  444. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $addt->line, $addt->field2column[$priority]);
  445. }
  446. $values = tripal_bulk_loader_add_foreignkey_to_values($table_data, $values, $data, $addt->record2priority, $addt->nid, $priority, $default_data);
  447. }
  448. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $addt->line);
  449. if (!$values) {
  450. //tripal_bulk_loader_throw_error('Line ' . $addt->line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), TRIPAL_NOTICE);
  451. }
  452. // get the table description
  453. $table_desc = chado_get_schema($table);
  454. if (!$table_desc) {
  455. $msg = "Tripal does not know about the table named '%table'. If this is a custom table,
  456. please define it first";
  457. tripal_bulk_loader_throw_error($msg, ['%table' => $table], TRIPAL_ERROR);
  458. $data[$priority]['error'] = TRUE;
  459. return;
  460. }
  461. // Check that template required fields are present. if a required field is
  462. // missing and this is an optional record then just return. otherwise raise
  463. // an error
  464. $skip_optional = 0;
  465. foreach ($table_data['required'] as $field => $required) {
  466. if ($required) {
  467. // check if the field has no value (or array is empty)
  468. if (!isset($values[$field]) or
  469. (is_array($values[$field]) and count($values[$field]) == 0)) {
  470. // check if the record is optional. For backwards compatiblity we need to
  471. // check if the 'mode' is set to 'optional'
  472. if ($table_data['optional'] or preg_match('/optional/', $table_data['mode']) or
  473. $table_data['select_optional']) {
  474. $skip_optional = 1;
  475. // set the values array to be empty since we all required fields are
  476. // optional and we can't do a select/insert so we don't want to keep
  477. // the values if this record is used in a later FK relationship.
  478. $values = [];
  479. }
  480. else {
  481. $msg = "Line " . $addt->line_num . ' "' . $table_data['record_id'] .
  482. '" (' . $table_data['mode'] . ') Missing template required value: ' . $table . '.' . $field;
  483. tripal_bulk_loader_throw_error($msg, [], TRIPAL_WARNING);
  484. $data[$priority]['error'] = TRUE;
  485. $no_errors = FALSE;
  486. }
  487. }
  488. }
  489. }
  490. // for an insert, check that all database required fields are present in the values array
  491. // we check for 'optional' in the mode for backwards compatibility. The 'optional'
  492. // mode used to be a type of insert
  493. if (!$skip_optional and (preg_match('/insert/', $table_data['mode']) or
  494. preg_match('/optional/', $table_data['mode']))) {
  495. // Check all database table required fields are set
  496. $fields = $table_desc['fields'];
  497. foreach ($fields as $field => $def) {
  498. // a field is considered missing if it cannot be null and there is no default
  499. // value for it or it is not of type 'serial'
  500. if (array_key_exists('not null', $def) and $def['not null'] == 1 and // field must have a value
  501. !array_key_exists($field, $values) and // there is not a value for it
  502. !array_key_exists('default', $def) and // there is no default for it
  503. strcmp($def['type'], 'serial') != 0) { // it is not a 'serial' type column
  504. $msg = "Line " . $addt->line_num . ' ' . $table_data['record_id'] .
  505. ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  506. tripal_bulk_loader_throw_error($msg, [], TRIPAL_ERROR);
  507. $data[$priority]['error'] = TRUE;
  508. $no_errors = FALSE;
  509. }
  510. }
  511. }
  512. // add updated values array into the data array
  513. $data[$priority]['values_array'] = $values;
  514. // if there was an error already -> don't insert
  515. if (array_key_exists('error', $data[$priority]) and $data[$priority]['error']) {
  516. tripal_bulk_loader_throw_error('Skipping processing of %table due to previous errors', ['%table' => $table], TRIPAL_NOTICE);
  517. return $no_errors;
  518. }
  519. // skip optional fields
  520. if ($skip_optional) {
  521. // SPF -- Commented out the following line. This state is intentional due
  522. // to the loader setup and and is not an error. If informational it
  523. // prints too much to the terminal.
  524. // tripal_bulk_loader_throw_error('Skipping an optional record (%record)',array('%record'=>$table_data['record_id']),TRIPAL_NOTICE);
  525. return $no_errors;
  526. }
  527. // check if it is already inserted
  528. if (array_key_exists('inserted', $table_data) and $table_data['inserted']) {
  529. // SPF -- Commented out the following line. This state is intentional due
  530. // to the loader setup and and is not an error. If informational it
  531. // prints too much to the terminal.
  532. // tripal_bulk_loader_throw_error('Skipping %record since it is already inserted',array('%record'=>$table_data['record_id']),TRIPAL_NOTICE);
  533. return $no_errors;
  534. }
  535. // check if it is already selected, if so, just get the value stored in
  536. // the default_data array
  537. if (array_key_exists('selected', $table_data) and $table_data['selected']) {
  538. $data[$priority]['values_array'] = $default_data[$priority]['values_array'];
  539. // SPF -- Commented out the following line. This state is intentional due
  540. // to the loader setup and and is not an error. If informational it
  541. // prints too much to the terminal.
  542. // tripal_bulk_loader_throw_error('%record was already selected thus we are just returning the values previously selected.',array('%record'=>$table_data['record_id']),TRIPAL_NOTICE);
  543. return $no_errors;
  544. }
  545. // make sure we have some value in the select_if_duplicate and update_if_duplicate options
  546. if (!array_key_exists('select_if_duplicate', $table_data)) {
  547. $table_data['select_if_duplicate'] = 0;
  548. }
  549. if (!array_key_exists('update_if_duplicate', $table_data)) {
  550. $table_data['update_if_duplicate'] = 0;
  551. }
  552. // if "select if duplicate" is enabled then check to ensure unique constraint is not violated.
  553. // If it is violated then simply return, the record already exists in the database.
  554. // We check for "insert_unique" for backwards compatibilty but that mode no longer exists
  555. $data[$priority]['is_duplicate'] = 0;
  556. if (preg_match('/insert_unique/', $table_data['mode']) or
  557. $table_data['select_if_duplicate'] == 1 or
  558. $table_data['update_if_duplicate'] == 1) {
  559. $options = ['is_duplicate' => TRUE, 'print_errors' => TRUE];
  560. $duplicate = chado_select_record($table, array_keys($table_desc['fields']), $values, $options);
  561. // if this is a duplicate then substitute the values in the table_data array so
  562. // that for future records that may depend on this one, they can get the values needed
  563. if ($duplicate and is_array($duplicate) and count($duplicate) == 1) {
  564. $dup_record = $duplicate[0];
  565. // save the duplicate record for later. If this is an update_if_duplicate
  566. // then we'll need this record as the match
  567. $data[$priority]['is_duplicate'] = (array) $dup_record;
  568. // if all we have is one field then we will just use the value returned
  569. // rather than create an array of values. This way it will prevent
  570. // the tripal_core_chado_(select|insert|update) from recursing on
  571. // foreign keys and make the loader go faster.
  572. if (count((array) $dup_record) == 1) {
  573. foreach ($dup_record as $key => $value) {
  574. $data[$priority]['values_array'] = $value;
  575. }
  576. }
  577. // if we have multiple fields returned then we need to set the values
  578. // the new array.
  579. else {
  580. // convert object to array
  581. $new_values = [];
  582. foreach ($dup_record as $key => $value) {
  583. $new_values[$key] = $value;
  584. }
  585. $data[$priority]['values_array'] = $new_values;
  586. }
  587. // return if this is a select_if_duplicate
  588. if ($table_data['select_if_duplicate'] == 1) {
  589. // SPF -- Commented out the following line. This state is intentional due
  590. // to the loader setup and and is not an error. If informational it
  591. // prints too much to the terminal.
  592. // tripal_bulk_loader_throw_error('Simply returning values for %record since it was already inserted',array('%record'=>$table_data['record_id']),TRIPAL_NOTICE);
  593. return $no_errors;
  594. }
  595. }
  596. }
  597. else {
  598. # TODO: what to do if there are more than one value returned when
  599. # checking for a duplicate?
  600. }
  601. if (!preg_match('/select/', $table_data['mode'])) {
  602. // Use prepared statement?
  603. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  604. $options = ['statement_name' => 'record_' . $addt->nid . '_' . $priority];
  605. if (($addt->line_num > 1 && $addt->group_index == 1) OR $addt->group_index > 1) {
  606. //$options['is_prepared'] = TRUE;
  607. }
  608. }
  609. else {
  610. $options = [];
  611. }
  612. // Skip chado_insert_record() built-in validation?
  613. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  614. $options['skip_validation'] = TRUE;
  615. }
  616. if ($table_data['update_if_duplicate'] == 1) {
  617. if (array_key_exists('statement_name', $options)) {
  618. $options['statement_name'] = 'upd_' . $options['statement_name'];
  619. }
  620. // This should have been set on the first round of inserts for this record
  621. $match = $data[$priority]['is_duplicate'];
  622. // However, sometimes there is a pre-existing record before the loader starts
  623. // Thus check that this value is set and if not, then generate a match array
  624. // based on the unique keys for this record.
  625. if (empty($match)) {
  626. $match = [];
  627. // First check to see if we have fields for the primary key
  628. foreach ($table_desc['primary key'] as $k_field) {
  629. if (!empty($values[$k_field])) {
  630. $match[$k_field] = $values[$k_field];
  631. }
  632. }
  633. // Otherwise check the fields that are part of the unique key
  634. if (empty($match)) {
  635. foreach ($table_desc['unique keys'] as $u_keys) {
  636. foreach ($u_keys as $u_field) {
  637. if (!empty($values[$u_field])) {
  638. $match[$u_field] = $values[$u_field];
  639. }
  640. }
  641. }
  642. }
  643. }
  644. if (!empty($match)) {
  645. // Now we need to check if it already exists via a select
  646. $results = chado_select_record($table, array_keys($table_desc['fields']), $match, ['print_errors' => TRUE]);
  647. // If not then insert
  648. if (empty($results)) {
  649. $options['statement_name'] = 'ins_' . $options['statement_name'];
  650. $options['print_errors'] = TRUE;
  651. $record = chado_insert_record($table, $values, $options);
  652. }
  653. else {
  654. $options['return_record'] = TRUE;
  655. $options['print_errors'] = TRUE;
  656. $record = chado_update_record($table, $match, $values, $options);
  657. }
  658. }
  659. else {
  660. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' .
  661. $table_data['mode'] . ') Unable to update record since none of the unique key or primary key fields were available ' .
  662. ' where values:' . print_r($values, TRUE);
  663. tripal_bulk_loader_throw_error($msg, [], TRIPAL_ERROR);
  664. $data[$priority]['error'] = TRUE;
  665. $no_errors = FALSE;
  666. }
  667. }
  668. else {
  669. $options['print_errors'] = TRUE;
  670. $record = chado_insert_record($table, $values, $options);
  671. }
  672. // if the insert was not successful
  673. if (!$record) {
  674. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' .
  675. $table_data['mode'] . ') Unable to insert record into ' . $table .
  676. ' where values:' . print_r($values, TRUE);
  677. tripal_bulk_loader_throw_error($msg, [], TRIPAL_ERROR);
  678. $data[$priority]['error'] = TRUE;
  679. $no_errors = FALSE;
  680. }
  681. // if the insert was succesful
  682. else {
  683. // if mode=insert_once then ensure we only insert it once
  684. if (preg_match('/insert_once/', $table_data['mode'])) {
  685. $default_data[$priority]['inserted'] = TRUE;
  686. }
  687. // add to tripal_bulk_loader_inserted
  688. if ($addt->node->keep_track_inserted) {
  689. $insert_record = db_query(
  690. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into=:table AND nid=:nid",
  691. [
  692. ':table' => $table,
  693. 'nid' => $addt->nid,
  694. ])->fetchObject();
  695. if ($insert_record) {
  696. $insert_record->ids_inserted .= ',' . $record[$table_desc['primary key'][0]];
  697. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  698. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  699. //return $no_errors;
  700. }
  701. else {
  702. $insert_record = [
  703. 'nid' => $addt->nid,
  704. 'table_inserted_into' => $table,
  705. 'table_primary_key' => $table_desc['primary key'][0],
  706. 'ids_inserted' => $record[$table_desc['primary key'][0]],
  707. ];
  708. //print 'New: '.print_r($insert_record,TRUE)."\n";
  709. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  710. //return $no_errors;
  711. }//end of if insert record
  712. }// end of if keeping track of records inserted
  713. // substitute the values array for the primary key if it exists
  714. // and is a single field
  715. if (array_key_exists('primary key', $table_desc)) {
  716. if (count($table_desc['primary key']) == 1) {
  717. $pkey_field = $table_desc['primary key'][0];
  718. $data[$priority]['values_array'] = $record[$pkey_field];
  719. }
  720. }
  721. else {
  722. //add changes back to values array
  723. $data[$priority]['values_array'] = $record;
  724. $values = $record;
  725. }
  726. } //end of if insert was successful
  727. }
  728. // perform a select
  729. else {
  730. // get the matches for this select
  731. $matches = [];
  732. if (is_array($values) and count($values) > 0) {
  733. $matches = chado_select_record($table, array_keys($table_desc['fields']), $values, ['print_errors' => TRUE]);
  734. }
  735. // if the record doesn't exist and it's not optional then generate an error
  736. if (count($matches) == 0) {
  737. // No record on select
  738. if ($table_data['select_optional'] != 1) {
  739. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  740. tripal_bulk_loader_throw_error($msg, [], TRIPAL_ERROR);
  741. $data[$priority]['error'] = TRUE;
  742. $no_errors = FALSE;
  743. }
  744. // there is no match and select optional is turned on, so we want to set
  745. // the values to empty for any records with an FK relationship on this one
  746. else {
  747. $data[$priority]['values_array'] = NULL;
  748. }
  749. }
  750. // if we have more than one record matching and this select isn't optional then fail
  751. if (count($matches) > 1) {
  752. if ($table_data['select_optional'] != 1) {
  753. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Too many matching records in ' . $table . ' where values:' . print_r($values, TRUE);
  754. tripal_bulk_loader_throw_error($msg, [], TRIPAL_WARNING);
  755. $data[$priority]['error'] = TRUE;
  756. $no_errors = FALSE;
  757. }
  758. // there are too many matches and this is an optional select so set
  759. // the values to empty for any records with an FK relationship on this one
  760. else {
  761. $data[$priority]['values_array'] = NULL;
  762. }
  763. }
  764. // if mode=select_once then ensure we only select it once
  765. if (preg_match('/select_once/', $table_data['mode'])) {
  766. $default_data[$priority]['selected'] = TRUE;
  767. // save the pkey
  768. if (array_key_exists('primary key', $table_desc)) {
  769. $new_values = [];
  770. foreach ($matches[0] as $key => $value) {
  771. $new_values[$key] = $value;
  772. }
  773. $default_data[$priority]['values_default'] = $new_values;
  774. }
  775. }
  776. }
  777. return $no_errors;
  778. }
  779. /**
  780. * This function adds the file data to the values array
  781. *
  782. * @param $values
  783. * The default values array -contains all constants
  784. * @param $line
  785. * An array of values for the current line
  786. * @param $field2column
  787. * An array mapping values fields to line columns
  788. *
  789. * @return
  790. * Supplemented values array
  791. *
  792. * @ingroup tripal_bulk_loader
  793. */
  794. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  795. foreach ($values as $field => $value) {
  796. if (is_array($value)) {
  797. continue;
  798. }
  799. $column = $field2column[$field] - 1;
  800. if ($column < 0) {
  801. continue;
  802. }
  803. if (preg_match('/\S+/', $line[$column])) {
  804. $values[$field] = $line[$column];
  805. }
  806. else {
  807. unset($values[$field]);
  808. }
  809. }
  810. return $values;
  811. }
  812. /**
  813. * Handles foreign keys in the values array.
  814. *
  815. * Specifically, if the value for a field is an array then it is assumed that
  816. * the array contains the name of the record whose values array should be
  817. * substituted here. Thus the foreign record is looked up and the values array
  818. * is substituted in.
  819. *
  820. * @ingroup tripal_bulk_loader
  821. */
  822. function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $data, $record2priority, $nid, $priority, $default_data) {
  823. // iterate through each field in the $values arrray and
  824. // substitute any values for FK / referring fields
  825. foreach ($values as $field => $value) {
  826. // if the field value is an array then it is an FK
  827. if (is_array($value)) {
  828. // get the name and priority of the foreign record
  829. $foreign_record = $value['foreign record']['record'];
  830. $foreign_priority = $record2priority[$foreign_record];
  831. $foreign_table = $value['foreign record']['table'];
  832. $foreign_field = $value['foreign record']['field'];
  833. // get the values of the foreign record and substitute those for the values
  834. $foreign_values = $data[$foreign_priority]['values_array'];
  835. // check to see if we have any default values in the $default_data array
  836. // these were populated from select statements that only need to run once
  837. // so we can reuse the values from those previous selects.
  838. if (array_key_exists($foreign_priority, $default_data) and
  839. array_key_exists('values_default', $default_data[$foreign_priority]) and
  840. array_key_exists($foreign_field, $default_data[$foreign_priority]['values_default'])) {
  841. $values[$field] = $default_data[$foreign_priority]['values_default'][$foreign_field];
  842. continue;
  843. }
  844. // if the field in the Referral records is in a FK relationship with
  845. // this field then we can simply keep the value we have
  846. $tbl_description = chado_get_schema($table_array['table']);
  847. if ($tbl_description and
  848. array_key_exists('foreign keys', $tbl_description) and
  849. array_key_exists($foreign_table, $tbl_description['foreign keys']) and
  850. array_key_exists($field, $tbl_description['foreign keys'][$foreign_table]['columns']) and
  851. $foreign_field == $tbl_description['foreign keys'][$foreign_table]['columns'][$field]) {
  852. $values[$field] = $foreign_values;
  853. }
  854. // if the field in the Referral records is not in an FK relationship
  855. // with this field then we we have to get the requested value, we must
  856. // return only a single value
  857. else {
  858. // if the current value of the referral records is a non-array then this
  859. // is the primary key, we can use it to select the value we need.
  860. $fk_description = chado_get_schema($foreign_table);
  861. if (!is_array($foreign_values)) {
  862. // if we have a value then use it to get the field we need
  863. if ($foreign_values) {
  864. $fvalues = [$fk_description['primary key'][0] => $foreign_values];
  865. $columns = [$foreign_field];
  866. $options = ['statement_name' => 'pk_' . $foreign_table];
  867. $options['print_errors'] = TRUE;
  868. $record = chado_select_record($foreign_table, $columns, $fvalues, $options);
  869. if ($record) {
  870. $values[$field] = $record[0]->$foreign_field;
  871. }
  872. else {
  873. unset($values[$field]);
  874. }
  875. }
  876. // if we don't have a value then there's nothing we can do so
  877. // set this value to nothing as well
  878. else {
  879. unset($values[$field]);
  880. }
  881. }
  882. // if the current value is an array and our field is not in it, then
  883. // we need to select a value for our field.
  884. else {
  885. $fvalues = $foreign_values;
  886. $columns = [$foreign_field];
  887. $options = ['statement_name' => 'blk_' . $nid . $priority . $foreign_table];
  888. $options['print_errors'] = TRUE;
  889. $record = chado_select_record($foreign_table, $columns, $fvalues, $options);
  890. if ($record) {
  891. $values[$field] = $record[0]->$foreign_field;
  892. }
  893. else {
  894. unset($values[$field]);
  895. }
  896. } // end else from: if (!is_array($foreign_values) ...
  897. } // end else from: if ($tbl_description ...
  898. } // end if(is_array($value)) ...
  899. } // end foreach ($values ...
  900. // return the updated field values
  901. return $values;
  902. }
  903. /**
  904. * Uses a supplied regex to transform spreadsheet values
  905. *
  906. * @param $values
  907. * The select/insert values array for the given table
  908. * @param $table_data
  909. * The data array for the given table
  910. *
  911. * @ingroup tripal_bulk_loader
  912. */
  913. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  914. if (!array_key_exists('regex_transform', $table_data) or
  915. empty($table_data['regex_transform']) or
  916. !array_key_exists('regex_transform', $table_data) or
  917. !is_array($table_data['regex_transform'])) {
  918. return $values;
  919. }
  920. //tripal_core_report_error('T_bulk_loader', TRIPAL_NOTICE,'Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array());
  921. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  922. if (!array_key_exists('replace', $regex_array) or
  923. !array_key_exists('pattern', $regex_array) or
  924. !is_array($regex_array['replace'])) {
  925. continue;
  926. }
  927. // Check for <#column:\d+#> notation
  928. // if present replace with that column in the current line
  929. foreach ($regex_array['replace'] as $key => $replace) {
  930. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  931. foreach ($matches[1] as $k => $column_num) {
  932. $replace = preg_replace('/' . $matches[0][$k] . '/', $line[$column_num - 1], $replace);
  933. }
  934. $regex_array['replace'][$key] = $replace;
  935. }
  936. }
  937. // do the full replacement
  938. $old_value = $values[$field];
  939. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  940. $values[$field] = $new_value;
  941. if ($values[$field] === '') {
  942. unset($values[$field]);
  943. }
  944. //print 'Now:'.$values[$field]."\n";
  945. }
  946. return $values;
  947. }
  948. /**
  949. * Flattens an array up to two levels
  950. * Used for printing of arrays without taking up much space
  951. *
  952. * @ingroup tripal_bulk_loader
  953. */
  954. function tripal_bulk_loader_flatten_array($values) {
  955. $flattened_values = [];
  956. foreach ($values as $k => $v) {
  957. if (is_array($v)) {
  958. $vstr = [];
  959. foreach ($v as $vk => $vv) {
  960. if (drupal_strlen($vv) > 20) {
  961. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  962. }
  963. else {
  964. $vstr[] = $vk . '=>' . $vv;
  965. }
  966. }
  967. $v = '{' . implode(',', $vstr) . '}';
  968. }
  969. elseif (drupal_strlen($v) > 20) {
  970. $v = drupal_substr($v, 0, 20) . '...';
  971. }
  972. $flattened_values[] = $k . '=>' . $v;
  973. }
  974. return implode(', ', $flattened_values);
  975. }
  976. /**
  977. * Used to display loader progress to the user
  978. *
  979. * @ingroup tripal_bulk_loader
  980. */
  981. function tripal_bulk_loader_progress_bar($current = 0, $total = 100, $size = 50) {
  982. $new_bar = FALSE;
  983. $mem = memory_get_usage();
  984. // First iteration
  985. if ($current == 0) {
  986. $new_bar = TRUE;
  987. fputs(STDOUT, "Progress:\n");
  988. }
  989. // Percentage round off for a more clean, consistent look
  990. $percent = sprintf("%.02f", round(($current / $total) * 100, 2));
  991. // percent indicator must be four characters, if shorter, add some spaces
  992. for ($i = strlen($percent); $i <= 4; $i++) {
  993. $percent = ' ' . $percent;
  994. }
  995. $total_size = $size + $i + 3 + 2;
  996. $place = 0;
  997. // if it's not first go, remove the previous bar
  998. if (!$new_bar) {
  999. for ($place = $total_size; $place > 0; $place--) {
  1000. // echo a backspace (hex:08) to remove the previous character
  1001. //echo "\x08";
  1002. }
  1003. }
  1004. // output the progess bar as it should be
  1005. // Start with a border
  1006. echo '[';
  1007. for ($place = 0; $place <= $size; $place++) {
  1008. // output "full" spaces if this portion is completed
  1009. if ($place <= ($current / $total * $size)) {
  1010. echo '|';
  1011. }
  1012. else {
  1013. // Otherwise empty space
  1014. echo '-';
  1015. }
  1016. }
  1017. // End with a border
  1018. echo ']';
  1019. // end a bar with a percent indicator
  1020. echo " $percent%. ($current of $total) Memory: $mem\r";
  1021. // if it's the end, add a new line
  1022. if ($current == $total) {
  1023. echo "\n";
  1024. }
  1025. }
  1026. /**
  1027. * Keep track of progress in file rather then database
  1028. *
  1029. * This provides an alternative method to keep track of progress that doesn't
  1030. * require the database. It was needed because you can't switch databases
  1031. * within a transaction... Waiting until the end of a constant set is much too
  1032. * long to wait for any indication that things are working.
  1033. *
  1034. * Each line represents a line processed in the loading file. Each period (.)
  1035. * represents a successfully inserted record.
  1036. *
  1037. * @param $job_id
  1038. * The ID of the current tripal job
  1039. * @param $record_added
  1040. * A boolean indicated whether a record was added successfully
  1041. * @param $line_complete
  1042. * A boolean indicating whether the current line is finished
  1043. * @param $close
  1044. * A boolean indicating that the file should be closed
  1045. *
  1046. * @ingroup tripal_bulk_loader
  1047. */
  1048. function tripal_bulk_loader_progress_file_track_job($job_id, $record_added, $line_complete = FALSE, $close = FALSE) {
  1049. // retrieve the file handle
  1050. $file_handle = variable_get('tripal_bulk_loader_progress_file_handle', NULL);
  1051. // open file for reading if not already
  1052. if (!$file_handle) {
  1053. $file_handle = fopen('/tmp/tripal_bulk_loader_progress-' . $job_id . '.out', 'w');
  1054. variable_set('tripal_bulk_loader_progress_file_handle', $file_handle);
  1055. }
  1056. if ($record_added) {
  1057. fwrite($file_handle, '.');
  1058. }
  1059. if ($line_complete) {
  1060. fwrite($file_handle, "\n");
  1061. }
  1062. // close the file if finished
  1063. if ($close) {
  1064. fclose($file_handle);
  1065. variable_set('tripal_bulk_loader_progress_file_handle', NULL);
  1066. }
  1067. }
  1068. /**
  1069. * Used to throw a hopefully human-readable error.
  1070. *
  1071. * @ingroup tripal_bulk_loader
  1072. */
  1073. function tripal_bulk_loader_throw_error($msg, $args, $severity) {
  1074. $options = ['print' => TRUE];
  1075. if ($severity == TRIPAL_NOTICE OR $severity == TRIPAL_INFO OR $severity == TRIPAL_DEBUG) {
  1076. unset($options['print']);
  1077. }
  1078. tripal_report_error(
  1079. 'tripal_bulk',
  1080. $severity,
  1081. $msg,
  1082. $args,
  1083. $options
  1084. );
  1085. }
  1086. /**
  1087. * Finishes the loading job by setting variables and exiting.
  1088. *
  1089. * @ingroup tripal_bulk_loader
  1090. */
  1091. function tripal_bulk_loader_finish_loading($nid, $loaded_without_errors) {
  1092. // set the status of the job (in the node not the tripal jobs)
  1093. if ($loaded_without_errors) {
  1094. $status = 'Loading Completed Successfully';
  1095. }
  1096. else {
  1097. $status = 'Errors Encountered';
  1098. }
  1099. db_update('tripal_bulk_loader')
  1100. ->fields(['job_status' => $status])
  1101. ->condition('nid', $nid)
  1102. ->execute();
  1103. if (!$loaded_without_errors) {
  1104. drush_set_error('BULK_LOAD_FAILED', 'Execution aborted due to errors.');
  1105. exit();
  1106. }
  1107. }