tripal_bulk_loader.loader.inc 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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. $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 = chado_get_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_set_job_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 = chado_get_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. // SPF -- Commented out the following line. This state is intentional due
  508. // to the loader setup and and is not an error. If informational it
  509. // prints too much to the terminal.
  510. // tripal_bulk_loader_throw_error('Skipping an optional record (%record)',array('%record'=>$table_data['record_id']),TRIPAL_NOTICE);
  511. return $no_errors;
  512. }
  513. // check if it is already inserted
  514. if (array_key_exists('inserted', $table_data) and $table_data['inserted']) {
  515. // SPF -- Commented out the following line. This state is intentional due
  516. // to the loader setup and and is not an error. If informational it
  517. // prints too much to the terminal.
  518. // tripal_bulk_loader_throw_error('Skipping %record since it is already inserted',array('%record'=>$table_data['record_id']),TRIPAL_NOTICE);
  519. return $no_errors;
  520. }
  521. // check if it is already selected, if so, just get the value stored in
  522. // the default_data array
  523. if (array_key_exists('selected', $table_data) and $table_data['selected']) {
  524. $data[$priority]['values_array'] = $default_data[$priority]['values_array'];
  525. // SPF -- Commented out the following line. This state is intentional due
  526. // to the loader setup and and is not an error. If informational it
  527. // prints too much to the terminal.
  528. // 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);
  529. return $no_errors;
  530. }
  531. // make sure we have some value in the select_if_duplicate and update_if_duplicate options
  532. if (!array_key_exists('select_if_duplicate', $table_data)) {
  533. $table_data['select_if_duplicate'] = 0;
  534. }
  535. if (!array_key_exists('update_if_duplicate', $table_data)) {
  536. $table_data['update_if_duplicate'] = 0;
  537. }
  538. // if "select if duplicate" is enabled then check to ensure unique constraint is not violated.
  539. // If it is violated then simply return, the record already exists in the database.
  540. // We check for "insert_unique" for backwards compatibilty but that mode no longer exists
  541. $data[$priority]['is_duplicate'] = 0;
  542. if (preg_match('/insert_unique/', $table_data['mode']) or
  543. $table_data['select_if_duplicate'] == 1 or
  544. $table_data['update_if_duplicate'] == 1) {
  545. $options = array('is_duplicate' => TRUE, 'print_errors' => TRUE);
  546. $duplicate = chado_select_record($table, array_keys($table_desc['fields']), $values, $options);
  547. // if this is a duplicate then substitute the values in the table_data array so
  548. // that for future records that may depend on this one, they can get the values needed
  549. if ($duplicate and is_array($duplicate) and count($duplicate) == 1) {
  550. $dup_record = $duplicate[0];
  551. // save the duplicate record for later. If this is an update_if_duplicate
  552. // then we'll need this record as the match
  553. $data[$priority]['is_duplicate'] = (array) $dup_record;
  554. // if all we have is one field then we will just use the value returned
  555. // rather than create an array of values. This way it will prevent
  556. // the tripal_core_chado_(select|insert|update) from recursing on
  557. // foreign keys and make the loader go faster.
  558. if (count((array) $dup_record) == 1) {
  559. foreach ($dup_record as $key => $value) {
  560. $data[$priority]['values_array'] = $value;
  561. }
  562. }
  563. // if we have multiple fields returned then we need to set the values
  564. // the new array.
  565. else {
  566. // convert object to array
  567. $new_values = array();
  568. foreach ($dup_record as $key => $value) {
  569. $new_values[$key] = $value;
  570. }
  571. $data[$priority]['values_array'] = $new_values;
  572. }
  573. // return if this is a select_if_duplicate
  574. if ($table_data['select_if_duplicate'] == 1) {
  575. // SPF -- Commented out the following line. This state is intentional due
  576. // to the loader setup and and is not an error. If informational it
  577. // prints too much to the terminal.
  578. // tripal_bulk_loader_throw_error('Simply returning values for %record since it was already inserted',array('%record'=>$table_data['record_id']),TRIPAL_NOTICE);
  579. return $no_errors;
  580. }
  581. }
  582. }
  583. else {
  584. # TODO: what to do if there are more than one value returned when
  585. # checking for a duplicate?
  586. }
  587. if (!preg_match('/select/', $table_data['mode'])) {
  588. // Use prepared statement?
  589. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  590. $options = array('statement_name' => 'record_' . $addt->nid . '_' . $priority);
  591. if (($addt->line_num > 1 && $addt->group_index == 1) OR $addt->group_index > 1) {
  592. //$options['is_prepared'] = TRUE;
  593. }
  594. }
  595. else {
  596. $options = array();
  597. }
  598. // Skip chado_insert_record() built-in validation?
  599. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  600. $options['skip_validation'] = TRUE;
  601. }
  602. if ($table_data['update_if_duplicate'] == 1) {
  603. if (array_key_exists('statement_name', $options)) {
  604. $options['statement_name'] = 'upd_' . $options['statement_name'];
  605. }
  606. // This should have been set on the first round of inserts for this record
  607. $match = $data[$priority]['is_duplicate'];
  608. // However, sometimes there is a pre-existing record before the loader starts
  609. // Thus check that this value is set and if not, then generate a match array
  610. // based on the unique keys for this record.
  611. if (empty($match)) {
  612. $match = array();
  613. // First check to see if we have fields for the primary key
  614. foreach ($table_desc['primary key'] as $k_field) {
  615. if (!empty($values[$k_field])) {
  616. $match[$k_field] = $values[$k_field];
  617. }
  618. }
  619. // Otherwise check the fields that are part of the unique key
  620. if (empty($match)) {
  621. foreach ($table_desc['unique keys'] as $u_keys) {
  622. foreach ($u_keys as $u_field) {
  623. if (!empty($values[$u_field])) {
  624. $match[$u_field] = $values[$u_field];
  625. }
  626. }
  627. }
  628. }
  629. }
  630. if (!empty($match)) {
  631. // Now we need to check if it already exists via a select
  632. $results = chado_select_record($table, array_keys($table_desc['fields']), $match, array('print_errors' => TRUE));
  633. // If not then insert
  634. if (empty($results)) {
  635. $options['statement_name'] = 'ins_'.$options['statement_name'];
  636. $options['print_errors'] = TRUE;
  637. $record = chado_insert_record($table, $values, $options);
  638. }
  639. else {
  640. $options['return_record'] = TRUE;
  641. $options['print_errors'] = TRUE;
  642. $record = chado_update_record($table, $match, $values, $options);
  643. }
  644. }
  645. else {
  646. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' .
  647. $table_data['mode'] . ') Unable to update record since none of the unique key or primary key fields were available ' .
  648. ' where values:' . print_r($values, TRUE);
  649. tripal_bulk_loader_throw_error($msg, array(), TRIPAL_ERROR);
  650. $data[$priority]['error'] = TRUE;
  651. $no_errors = FALSE;
  652. }
  653. }
  654. else {
  655. $options['print_errors'] = TRUE;
  656. $record = chado_insert_record($table, $values, $options);
  657. }
  658. // if the insert was not successful
  659. if (!$record) {
  660. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' .
  661. $table_data['mode'] . ') Unable to insert record into ' . $table .
  662. ' where values:' . print_r($values, TRUE);
  663. tripal_bulk_loader_throw_error($msg, array(), TRIPAL_ERROR);
  664. $data[$priority]['error'] = TRUE;
  665. $no_errors = FALSE;
  666. }
  667. // if the insert was succesful
  668. else {
  669. // if mode=insert_once then ensure we only insert it once
  670. if (preg_match('/insert_once/', $table_data['mode'])) {
  671. $default_data[$priority]['inserted'] = TRUE;
  672. }
  673. // add to tripal_bulk_loader_inserted
  674. if ($addt->node->keep_track_inserted) {
  675. $insert_record = db_query(
  676. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into=:table AND nid=:nid",
  677. array(
  678. ':table' => $table,
  679. 'nid' => $addt->nid
  680. ))->fetchObject();
  681. if ($insert_record) {
  682. $insert_record->ids_inserted .= ',' . $record[$table_desc['primary key'][0] ];
  683. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  684. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  685. //return $no_errors;
  686. }
  687. else {
  688. $insert_record = array(
  689. 'nid' => $addt->nid,
  690. 'table_inserted_into' => $table,
  691. 'table_primary_key' => $table_desc['primary key'][0],
  692. 'ids_inserted' => $record[ $table_desc['primary key'][0] ],
  693. );
  694. //print 'New: '.print_r($insert_record,TRUE)."\n";
  695. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  696. //return $no_errors;
  697. }//end of if insert record
  698. }// end of if keeping track of records inserted
  699. // substitute the values array for the primary key if it exists
  700. // and is a single field
  701. if (array_key_exists('primary key', $table_desc)) {
  702. if (count($table_desc['primary key']) == 1) {
  703. $pkey_field = $table_desc['primary key'][0];
  704. $data[$priority]['values_array'] = $record[$pkey_field];
  705. }
  706. }
  707. else {
  708. //add changes back to values array
  709. $data[$priority]['values_array'] = $record;
  710. $values = $record;
  711. }
  712. } //end of if insert was successful
  713. }
  714. // perform a select
  715. else {
  716. // get the matches for this select
  717. $matches = array();
  718. if (is_array($values) and count($values) > 0) {
  719. $matches = chado_select_record($table, array_keys($table_desc['fields']), $values, array('print_errors' => TRUE));
  720. }
  721. // if the record doesn't exist and it's not optional then generate an error
  722. if (count($matches) == 0) {
  723. // No record on select
  724. if ($table_data['select_optional'] != 1) {
  725. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  726. tripal_bulk_loader_throw_error($msg, array(), TRIPAL_ERROR);
  727. $data[$priority]['error'] = TRUE;
  728. $no_errors = FALSE;
  729. }
  730. // there is no match and select optional is turned on, so we want to set
  731. // the values to empty for any records with an FK relationship on this one
  732. else {
  733. $data[$priority]['values_array'] = NULL;
  734. }
  735. }
  736. // if we have more than one record matching and this select isn't optional then fail
  737. if (count($matches) > 1) {
  738. if ($table_data['select_optional'] != 1) {
  739. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Too many matching records in ' . $table . ' where values:' . print_r($values, TRUE);
  740. tripal_bulk_loader_throw_error($msg, array(), TRIPAL_WARNING);
  741. $data[$priority]['error'] = TRUE;
  742. $no_errors = FALSE;
  743. }
  744. // there are too many matches and this is an optional select so set
  745. // the values to empty for any records with an FK relationship on this one
  746. else {
  747. $data[$priority]['values_array'] = NULL;
  748. }
  749. }
  750. // if mode=select_once then ensure we only select it once
  751. if (preg_match('/select_once/', $table_data['mode'])) {
  752. $default_data[$priority]['selected'] = TRUE;
  753. // save the pkey
  754. if (array_key_exists('primary key', $table_desc)) {
  755. $new_values = array();
  756. foreach ($matches[0] as $key => $value) {
  757. $new_values[$key] = $value;
  758. }
  759. $default_data[$priority]['values_default'] = $new_values;
  760. }
  761. }
  762. }
  763. return $no_errors;
  764. }
  765. /**
  766. * This function adds the file data to the values array
  767. *
  768. * @param $values
  769. * The default values array -contains all constants
  770. * @param $line
  771. * An array of values for the current line
  772. * @param $field2column
  773. * An array mapping values fields to line columns
  774. * @return
  775. * Supplemented values array
  776. *
  777. * @ingroup tripal_bulk_loader
  778. */
  779. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  780. foreach ($values as $field => $value) {
  781. if (is_array($value)) {
  782. continue;
  783. }
  784. $column = $field2column[$field] - 1;
  785. if ($column < 0) {
  786. continue;
  787. }
  788. if (preg_match('/\S+/', $line[$column])) {
  789. $values[$field] = $line[$column];
  790. }
  791. else {
  792. unset($values[$field]);
  793. }
  794. }
  795. return $values;
  796. }
  797. /**
  798. * Handles foreign keys in the values array.
  799. *
  800. * Specifically, if the value for a field is an array then it is assumed that the array contains
  801. * the name of the record whose values array should be substituted here. Thus the foreign
  802. * record is looked up and the values array is substituted in.
  803. *
  804. * @ingroup tripal_bulk_loader
  805. */
  806. function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $data, $record2priority, $nid, $priority, $default_data) {
  807. // iterate through each field in the $values arrray and
  808. // substitute any values for FK / referring fields
  809. foreach ($values as $field => $value) {
  810. // if the field value is an array then it is an FK
  811. if (is_array($value)) {
  812. // get the name and priority of the foreign record
  813. $foreign_record = $value['foreign record']['record'];
  814. $foreign_priority = $record2priority[$foreign_record];
  815. $foreign_table = $value['foreign record']['table'];
  816. $foreign_field = $value['foreign record']['field'];
  817. // get the values of the foreign record and substitute those for the values
  818. $foreign_values = $data[$foreign_priority]['values_array'];
  819. // check to see if we have any default values in the $default_data array
  820. // these were populated from select statements that only need to run once
  821. // so we can reuse the values from those previous selects.
  822. if (array_key_exists($foreign_priority, $default_data) and
  823. array_key_exists('values_default', $default_data[$foreign_priority]) and
  824. array_key_exists($foreign_field, $default_data[$foreign_priority]['values_default'])) {
  825. $values[$field] = $default_data[$foreign_priority]['values_default'][$foreign_field];
  826. continue;
  827. }
  828. // if the field in the Referral records is in a FK relationship with
  829. // this field then we can simply keep the value we have
  830. $tbl_description = chado_get_schema($table_array['table']);
  831. if ($tbl_description and
  832. array_key_exists('foreign keys', $tbl_description) and
  833. array_key_exists($foreign_table, $tbl_description['foreign keys']) and
  834. array_key_exists($field, $tbl_description['foreign keys'][$foreign_table]['columns']) and
  835. $foreign_field == $tbl_description['foreign keys'][$foreign_table]['columns'][$field]) {
  836. $values[$field] = $foreign_values;
  837. }
  838. // if the field in the Referral records is not in an FK relationship
  839. // with this field then we we have to get the requested value, we must
  840. // return only a single value
  841. else {
  842. // if the current value of the referral records is a non-array then this
  843. // is the primary key, we can use it to select the value we need.
  844. $fk_description = chado_get_schema($foreign_table);
  845. if (!is_array($foreign_values)) {
  846. // if we have a value then use it to get the field we need
  847. if ($foreign_values) {
  848. $fvalues = array($fk_description['primary key'][0] => $foreign_values);
  849. $columns = array($foreign_field);
  850. $options = array('statement_name' => 'pk_' . $foreign_table);
  851. $options['print_errors'] = TRUE;
  852. $record = chado_select_record($foreign_table, $columns, $fvalues, $options);
  853. if ($record) {
  854. $values[$field] = $record[0]->$foreign_field;
  855. }
  856. else {
  857. unset($values[$field]);
  858. }
  859. }
  860. // if we don't have a value then there's nothing we can do so
  861. // set this value to nothing as well
  862. else {
  863. unset($values[$field]);
  864. }
  865. }
  866. // if the current value is an array and our field is not in it, then
  867. // we need to select a value for our field.
  868. else {
  869. $fvalues = $foreign_values;
  870. $columns = array($foreign_field);
  871. $options = array('statement_name' => 'blk_' . $nid . $priority . $foreign_table);
  872. $options['print_errors'] = TRUE;
  873. $record = chado_select_record($foreign_table, $columns, $fvalues, $options);
  874. if ($record) {
  875. $values[$field] = $record[0]->$foreign_field;
  876. }
  877. else {
  878. unset($values[$field]);
  879. }
  880. } // end else from: if (!is_array($foreign_values) ...
  881. } // end else from: if ($tbl_description ...
  882. } // end if(is_array($value)) ...
  883. } // end foreach ($values ...
  884. // return the updated field values
  885. return $values;
  886. }
  887. /**
  888. * Uses a supplied regex to transform spreadsheet values
  889. *
  890. * @param $values
  891. * The select/insert values array for the given table
  892. * @param $table_data
  893. * The data array for the given table
  894. *
  895. * @ingroup tripal_bulk_loader
  896. */
  897. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  898. if (!array_key_exists('regex_transform', $table_data) or
  899. empty($table_data['regex_transform']) or
  900. !array_key_exists('regex_transform', $table_data) or
  901. !is_array($table_data['regex_transform'])) {
  902. return $values;
  903. }
  904. //tripal_core_report_error('T_bulk_loader', TRIPAL_NOTICE,'Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array());
  905. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  906. if (!array_key_exists('replace', $regex_array) or
  907. !array_key_exists('pattern', $regex_array) or
  908. !is_array($regex_array['replace'])) {
  909. continue;
  910. }
  911. // Check for <#column:\d+#> notation
  912. // if present replace with that column in the current line
  913. foreach ($regex_array['replace'] as $key => $replace) {
  914. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  915. foreach ($matches[1] as $k => $column_num) {
  916. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  917. }
  918. $regex_array['replace'][$key] = $replace;
  919. }
  920. }
  921. // do the full replacement
  922. $old_value = $values[$field];
  923. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  924. $values[$field] = $new_value;
  925. if ($values[$field] === '') {
  926. unset($values[$field]);
  927. }
  928. //print 'Now:'.$values[$field]."\n";
  929. }
  930. return $values;
  931. }
  932. /**
  933. * Flattens an array up to two levels
  934. * Used for printing of arrays without taking up much space
  935. *
  936. * @ingroup tripal_bulk_loader
  937. */
  938. function tripal_bulk_loader_flatten_array($values) {
  939. $flattened_values = array();
  940. foreach ($values as $k => $v) {
  941. if (is_array($v)) {
  942. $vstr = array();
  943. foreach ($v as $vk => $vv) {
  944. if (drupal_strlen($vv) > 20) {
  945. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  946. }
  947. else {
  948. $vstr[] = $vk . '=>' . $vv;
  949. }
  950. }
  951. $v = '{' . implode(',', $vstr) . '}';
  952. }
  953. elseif (drupal_strlen($v) > 20) {
  954. $v = drupal_substr($v, 0, 20) . '...';
  955. }
  956. $flattened_values[] = $k . '=>' . $v;
  957. }
  958. return implode(', ', $flattened_values);
  959. }
  960. /**
  961. * Used to display loader progress to the user
  962. *
  963. * @ingroup tripal_bulk_loader
  964. */
  965. function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
  966. $new_bar = FALSE;
  967. $mem = memory_get_usage();
  968. // First iteration
  969. if ($current == 0) {
  970. $new_bar = TRUE;
  971. fputs(STDOUT, "Progress:\n");
  972. }
  973. // Percentage round off for a more clean, consistent look
  974. $percent = sprintf("%.02f", round(($current/$total) * 100, 2));
  975. // percent indicator must be four characters, if shorter, add some spaces
  976. for ($i = strlen($percent); $i <= 4; $i++) {
  977. $percent = ' ' . $percent;
  978. }
  979. $total_size = $size + $i + 3 + 2;
  980. $place = 0;
  981. // if it's not first go, remove the previous bar
  982. if (!$new_bar) {
  983. for ($place = $total_size; $place > 0; $place--) {
  984. // echo a backspace (hex:08) to remove the previous character
  985. //echo "\x08";
  986. }
  987. }
  988. // output the progess bar as it should be
  989. // Start with a border
  990. echo '[';
  991. for ($place = 0; $place <= $size; $place++) {
  992. // output "full" spaces if this portion is completed
  993. if ($place <= ($current / $total * $size)) {
  994. echo '|';
  995. }
  996. else {
  997. // Otherwise empty space
  998. echo '-';
  999. }
  1000. }
  1001. // End with a border
  1002. echo ']';
  1003. // end a bar with a percent indicator
  1004. echo " $percent%. ($current of $total) Memory: $mem\r";
  1005. // if it's the end, add a new line
  1006. if ($current == $total) {
  1007. echo "\n";
  1008. }
  1009. }
  1010. /**
  1011. * Keep track of progress in file rather then database
  1012. *
  1013. * This provides an alternative method to keep track of progress that doesn't require the
  1014. * database. It was needed because you can't switch databases within a transaction...
  1015. * Waiting until the end of a constant set is much too long to wait for any indication
  1016. * that things are working.
  1017. *
  1018. * Each line represents a line processed in the loading file. Each period (.) represents
  1019. * a successfully inserted record.
  1020. *
  1021. * @param $job_id
  1022. * The ID of the current tripal job
  1023. * @param $record_added
  1024. * A boolean indicated whether a record was added successfully
  1025. * @param $line_complete
  1026. * A boolean indicating whether the current line is finished
  1027. * @param $close
  1028. * A boolean indicating that the file should be closed
  1029. *
  1030. * @ingroup tripal_bulk_loader
  1031. */
  1032. function tripal_bulk_loader_progress_file_track_job($job_id, $record_added, $line_complete = FALSE, $close = FALSE) {
  1033. // retrieve the file handle
  1034. $file_handle = variable_get('tripal_bulk_loader_progress_file_handle', NULL);
  1035. // open file for reading if not already
  1036. if (!$file_handle) {
  1037. $file_handle = fopen('/tmp/tripal_bulk_loader_progress-'. $job_id . '.out', 'w');
  1038. variable_set('tripal_bulk_loader_progress_file_handle', $file_handle);
  1039. }
  1040. if ($record_added) {
  1041. fwrite($file_handle, '.');
  1042. }
  1043. if ($line_complete) {
  1044. fwrite($file_handle, "\n");
  1045. }
  1046. // close the file if finished
  1047. if ($close) {
  1048. fclose($file_handle);
  1049. variable_set('tripal_bulk_loader_progress_file_handle', NULL);
  1050. }
  1051. }
  1052. /**
  1053. * Used to throw a hopefully human-readable error.
  1054. *
  1055. * @ingroup tripal_bulk_loader
  1056. */
  1057. function tripal_bulk_loader_throw_error($msg, $args, $severity) {
  1058. $options = array('print' => TRUE);
  1059. if ($severity == TRIPAL_NOTICE OR $severity == TRIPAL_INFO OR $severity == TRIPAL_DEBUG) {
  1060. unset($options['print']);
  1061. }
  1062. tripal_report_error(
  1063. 'tripal_bulk',
  1064. $severity,
  1065. $msg,
  1066. $args,
  1067. $options
  1068. );
  1069. }
  1070. /**
  1071. * Finishes the loading job by setting variables and exiting.
  1072. *
  1073. * @ingroup tripal_bulk_loader
  1074. */
  1075. function tripal_bulk_loader_finish_loading($nid, $loaded_without_errors) {
  1076. // set the status of the job (in the node not the tripal jobs)
  1077. if ($loaded_without_errors) {
  1078. $status = 'Loading Completed Successfully';
  1079. }
  1080. else {
  1081. $status = 'Errors Encountered';
  1082. }
  1083. db_update('tripal_bulk_loader')
  1084. ->fields(array('job_status' => $status))
  1085. ->condition('nid', $nid)
  1086. ->execute();
  1087. if(!$loaded_without_errors) {
  1088. drush_set_error('BULK_LOAD_FAILED', 'Execution aborted due to errors.');
  1089. exit();
  1090. }
  1091. }