tripal_bulk_loader.loader.inc 37 KB

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