tripal_bulk_loader.loader.inc 43 KB

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