tripal_bulk_loader.loader.inc 43 KB

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