tripal_bulk_loader.loader.inc 42 KB

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