tripal_bulk_loader.loader.inc 43 KB

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