tripal_bulk_loader.loader.inc 45 KB

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