tripal_bulk_loader.loader.inc 45 KB

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