tripal_bulk_loader.loader.inc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. if (($node->job_status == 'Loading...') AND (variable_get('tripal_bulk_loader_transactions', 'row') != 'none')) {
  15. drupal_set_message("Job Progress and Loading Summary will only be updated at the end of each constant set.","warning");
  16. }
  17. $form['nid'] = array(
  18. '#type' => 'hidden',
  19. '#value' => $node->nid,
  20. );
  21. $form['file'] = array(
  22. '#type' => 'hidden',
  23. '#value' => $node->file
  24. );
  25. $form['job_id'] = array(
  26. '#type' => 'hidden',
  27. '#value' => $node->job_id,
  28. );
  29. $form['submit'] = array(
  30. '#type' => 'submit',
  31. '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
  32. );
  33. $form['submit-cancel'] = array(
  34. '#type' => ($node->job_id)? 'submit' : 'hidden',
  35. '#value' => 'Cancel Job',
  36. );
  37. $form['submit-revert'] = array(
  38. '#type' => ($node->job_id) ? 'submit' : 'hidden',
  39. '#value' => 'Revert',
  40. );
  41. return $form;
  42. }
  43. /**
  44. * Add Loader Job Form (Submit)
  45. */
  46. function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
  47. global $user;
  48. if (preg_match('/Submit Job/', $form_state['values']['op'])) {
  49. //Submit Tripal Job
  50. $job_args[1] = $form_state['values']['nid'];
  51. if (is_readable($form_state['values']['file'])) {
  52. $fname = basename($form_state['values']['file']);
  53. $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
  54. // add job_id to bulk_loader node
  55. $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
  56. // change status
  57. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  58. }
  59. else {
  60. drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $form_state['values']['file'])));
  61. }
  62. }
  63. elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
  64. tripal_jobs_rerun($form_state['values']['job_id']);
  65. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  66. }
  67. elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
  68. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Job Cancelled', $form_state['values']['nid']);
  69. tripal_jobs_cancel($form_state['values']['job_id']);
  70. }
  71. elseif (preg_match('/Revert/', $form_state['values']['op'])) {
  72. // Remove the records from the database that were already inserted
  73. $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d ORDER BY tripal_bulk_loader_inserted_id DESC', $form_state['values']['nid']);
  74. while ($r = db_fetch_object($resource)) {
  75. $ids = preg_split('/,/', $r->ids_inserted);
  76. db_query('DELETE FROM %s WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
  77. $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));
  78. if (!$result->present) {
  79. drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', array('%tableto' => $r->table_inserted_into)));
  80. db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d', $r->tripal_bulk_loader_inserted_id);
  81. }
  82. else {
  83. drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', array('%tableto' => $r->table_inserted_into)), 'error');
  84. }
  85. }
  86. // reset status
  87. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Reverted -Data Deleted', $form_state['values']['nid']);
  88. }
  89. }
  90. /**
  91. * Tripal Bulk Loader
  92. *
  93. * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  94. *
  95. * @param $nid
  96. * The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  97. * in the node (ie: template ID and file)
  98. *
  99. * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
  100. * Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
  101. */
  102. function tripal_bulk_loader_load_data($nid) {
  103. // ensure no timeout
  104. set_time_limit(0);
  105. // set the status of the job (in the node not the tripal jobs)
  106. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Loading...', $nid);
  107. $node = node_load($nid);
  108. print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
  109. $total_lines = trim(`wc --lines < $node->file`);
  110. print "File: " . $node->file . " (" . $total_lines . " lines)\n";
  111. // Prep Work ==================================================================================
  112. $loaded_without_errors = TRUE;
  113. // Generate default values array
  114. $default_data = array();
  115. $field2column = array();
  116. $record2priority = array();
  117. $tables = array();
  118. foreach ($node->template->template_array as $priority => $record_array) {
  119. if (!is_array($record_array)) {
  120. continue;
  121. }
  122. // Add tables being inserted into to a list to be treated differently
  123. // this is used to acquire locks on these tables
  124. if (preg_match('/insert/', $record_array['mode'])) {
  125. $tables[$record_array['table']] = $record_array['table'];
  126. }
  127. foreach ($record_array['fields'] as $field_index => $field_array) {
  128. $default_data[$priority]['table'] = $record_array['table'];
  129. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert_unique';
  130. $default_data[$priority]['record_id'] = $record_array['record_id'];
  131. $record2priority[$record_array['record_id']] = $priority;
  132. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  133. $one = $default_data[$priority];
  134. if (isset($field_array['regex'])) {
  135. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  136. }
  137. $two = $default_data[$priority];
  138. if (preg_match('/table field/', $field_array['type'])) {
  139. $default_data[$priority]['values_array'][$field_array['field']] = '';
  140. $default_data[$priority]['need_further_processing'] = TRUE;
  141. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  142. }
  143. elseif (preg_match('/constant/', $field_array['type'])) {
  144. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  145. }
  146. elseif (preg_match('/foreign key/', $field_array['type'])) {
  147. $default_data[$priority]['values_array'][$field_array['field']] = array();
  148. $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
  149. $default_data[$priority]['need_further_processing'] = TRUE;
  150. }
  151. else {
  152. print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
  153. }
  154. $three = $default_data[$priority];
  155. //watchdog('T_bulk_loader','A)'.$field_index.':<pre>Field Array =>'.print_r($field_array,TRUE)."Initial => \n".print_r($one, TRUE)."\nAfter Regex =>".print_r($two, TRUE)."Final =>\n".print_r($three,TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  156. } // end of foreach field
  157. //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  158. } //end of foreach record
  159. ///////////////////////////////////////////////
  160. // For each set of constants
  161. ///////////////////////////////////////////////
  162. $original_default_data = $default_data;
  163. $group_index = 0;
  164. $total_num_groups = sizeof($node->constants);
  165. foreach ($node->constants as $group_id => $set) {
  166. // revert default data array for next set of constants
  167. $default_data = $original_default_data;
  168. $group_index++;
  169. // Add constants
  170. if (!empty($set)) {
  171. print "Constants:\n";
  172. foreach ($set as $priority => $record) {
  173. foreach ($record as $field_id => $field) {
  174. print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
  175. if ($default_data[$priority]['table'] == $field['chado_table']) {
  176. if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
  177. if (isset($field2column[$priority][$field['chado_field']])) {
  178. $field2column[$priority][$field['chado_field']] = $field['value'];
  179. }
  180. else {
  181. $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
  182. }
  183. }
  184. else {
  185. print "ERROR: Template has changed after constants were assigned!\n";
  186. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  187. exit(1);
  188. }
  189. }
  190. else {
  191. print "ERROR: Template has changed after constants were assigned!\n";
  192. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  193. exit(1);
  194. }
  195. }
  196. }
  197. }
  198. //print "Default Data:".print_r($default_data,TRUE)."\n";
  199. //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  200. //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
  201. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  202. // Parse File adding records as we go ========================================================
  203. // Open File
  204. $file_handle = fopen($node->file, 'r');
  205. // Set defaults
  206. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  207. fgets($file_handle, 4096);
  208. }
  209. $num_records = 0;
  210. $num_lines = 0;
  211. $num_errors = 0;
  212. $interval = intval($total_lines * 0.10);
  213. if ($interval == 0) {
  214. $interval = 1;
  215. }
  216. // Start Transaction
  217. switch (variable_get('tripal_bulk_loader_transactions', 'row')) {
  218. case "none":
  219. break;
  220. case "all":
  221. tripal_db_start_transaction();
  222. $transactions = TRUE;
  223. $savepoint = "";
  224. break;
  225. case "row":
  226. tripal_db_start_transaction();
  227. $transactions = TRUE;
  228. $savepoint = "last_row_complete";
  229. break;
  230. }
  231. // Disable triggers
  232. $triggers_disabled = FALSE;
  233. if ($transactions AND variable_get('tripal_bulk_loader_disable_triggers', TRUE)) {
  234. $triggers_disabled = TRUE;
  235. chado_query("SET CONSTRAINTS ALL DEFERRED");
  236. }
  237. // Acquire Locks
  238. $lockmode = variable_get('tripal_bulk_loader_lock', 'ROW EXCLUSIVE');
  239. foreach ($tables as $table) {
  240. chado_query("LOCK TABLE %s IN %s MODE", $table, $lockmode);
  241. }
  242. tripal_bulk_loader_progress_bar(0,$total_lines);
  243. while (!feof($file_handle)) {
  244. // Clear variables
  245. // Was added to fix memory leak
  246. unset($line); unset($raw_line);
  247. unset($data); unset($data_keys);
  248. unset($priority); unset($sql);
  249. unset($result);
  250. $raw_line = fgets($file_handle, 4096);
  251. $raw_line = trim($raw_line);
  252. if (empty($raw_line)) {
  253. continue;
  254. } // skips blank lines
  255. $line = explode("\t", $raw_line);
  256. $num_lines++;
  257. // update the job status every 10% of lines processed for the current group
  258. if ($node->job_id and $num_lines % $interval == 0) {
  259. // percentage of lines processed for the current group
  260. $group_progress = round(($num_lines/$total_lines)*100);
  261. tripal_bulk_loader_progress_bar($num_lines,$total_lines);
  262. // percentage of lines processed for all groups
  263. // <previous group index> * 100 + <current group progress>
  264. // --------------------------------------------------------
  265. // <total number of groups>
  266. // For example, if you were in the third group of 3 constant sets
  267. // and had a group percentage of 50% then the job progress would be
  268. // (2*100 + 50%) / 3 = 250%/3 = 83%
  269. $job_progress = round(((($group_index-1)*100)+$group_progress)/$total_num_groups);
  270. tripal_job_set_progress($node->job_id, $job_progress);
  271. }
  272. $data = $default_data;
  273. $data_keys = array_keys($data);
  274. foreach ($data_keys as $priority) {
  275. $status = process_data_array_for_line($priority, $data, $default_data, $field2column, $record2priority, $line, $nid, $num_lines, $group_index);
  276. if (!$status ) {
  277. // Encountered an error
  278. if ($transactions) {
  279. tripal_db_rollback_transaction($savepoint);
  280. }
  281. $failed = TRUE;
  282. break;
  283. }
  284. } // end of foreach table in default data array
  285. if ($failed) {
  286. break;
  287. }
  288. else {
  289. // Row inserted successfully
  290. // Set savepoint if supplied
  291. if ($savepoint) {
  292. if ($num_lines == 1) {
  293. tripal_db_set_savepoint_transaction($savepoint);
  294. }
  295. else {
  296. // Tell it to remove the previous savepoint of the same name
  297. tripal_db_set_savepoint_transaction($savepoint, TRUE);
  298. }
  299. }
  300. }
  301. } //end of foreach line of file
  302. // END Transaction
  303. if ($transactions) {
  304. // end the transaction
  305. tripal_db_commit_transaction();
  306. }
  307. if ($failed) {
  308. $loaded_without_errors = FALSE;
  309. break;
  310. }
  311. tripal_bulk_loader_progress_bar($total_lines,$total_lines);
  312. } //end of foreach constant set
  313. // check that data was inserted and update job_status
  314. $sql = 'SELECT count(*) as num_tables FROM {tripal_bulk_loader_inserted} WHERE nid=%d GROUP BY nid';
  315. $result = db_fetch_object(db_query($sql, $nid));
  316. if ($result->num_tables > 0) {
  317. $node->job_status = 'Data Inserted';
  318. drupal_write_record('node', $node, 'nid');
  319. }
  320. // set the status of the job (in the node not the tripal jobs)
  321. if ($loaded_without_errors) {
  322. $status = 'Loading Completed Successfully';
  323. }
  324. else {
  325. $status = 'Errors Encountered';
  326. }
  327. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
  328. }
  329. /**
  330. *
  331. *
  332. */
  333. function process_data_array_for_line($priority, &$data, &$default_data, $field2column, $record2priority, $line, $nid, $line_num, $group_index) {
  334. $table_data = $data[$priority];
  335. $no_errors = TRUE;
  336. $table = $table_data['table'];
  337. $values = $table_data['values_array'];
  338. //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  339. //print 'default values:'.print_r($values,TRUE)."\n";
  340. if ($table_data['need_further_processing']) {
  341. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column[$priority]);
  342. if (!$values) {
  343. //watchdog('T_bulk_loader', 'Line ' . $line_num . ' Data File Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  344. }
  345. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority);
  346. if (!$values) {
  347. //watchdog('T_bulk_loader', 'Line ' . $line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
  348. }
  349. }
  350. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $line);
  351. if (!$values) {
  352. //watchdog('T_bulk_loader', 'Line ' . $line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
  353. }
  354. if (!$values) {
  355. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Aborted due to error in previous record. Values of current record:' . print_r($table_data['values_array'], TRUE);
  356. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  357. print "ERROR: " . $msg . "\n";
  358. $data[$priority]['error'] = TRUE;
  359. $no_errors = FALSE;
  360. }
  361. $table_desc = module_invoke_all('chado_' . $table . '_schema');
  362. if (preg_match('/optional/', $table_array['mode'])) {
  363. // Check all db required fields are set
  364. $fields = $table_desc['fields'];
  365. foreach ($fields as $field => $def) {
  366. // a field is considered missing if it cannot be null and there is no default
  367. // value for it or it is of type 'serial'
  368. if ($def['not null'] == 1 and !array_key_exists($field, $insert_values) and !isset($def['default']) and strcmp($def['type'], serial)!=0) {
  369. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  370. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  371. $data[$priority]['error'] = TRUE;
  372. }
  373. }
  374. } //end of if optional record
  375. // Check required fields are present
  376. foreach ($table_data['required'] as $field => $required) {
  377. if ($required) {
  378. if (!isset($values[$field])) {
  379. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
  380. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  381. $data[$priority]['error'] = TRUE;
  382. }
  383. }
  384. }
  385. // add new values array into the data array
  386. $data[$priority]['values_array'] = $values;
  387. // check if it is already inserted
  388. if ($table_data['inserted']) {
  389. //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
  390. return $no_errors;
  391. }
  392. // if there was an error already -> don't insert
  393. if ($data[$priority]['error']) {
  394. return $no_errors;
  395. }
  396. $header = '';
  397. if (isset($values['feature_id'])) {
  398. $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
  399. }
  400. else {
  401. $header = $values['uniquename'] . ' ' . $table_data['record_id'];
  402. }
  403. // if insert unique then check to ensure unique
  404. if (preg_match('/insert_unique/', $table_data['mode'])) {
  405. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  406. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  407. if ($unique > 0) {
  408. //$default_data[$priority]['inserted'] = TRUE;
  409. //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
  410. return $no_errors;
  411. }
  412. }
  413. if (!preg_match('/select/', $table_data['mode'])) {
  414. // Use prepared statement?
  415. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  416. $options = array('statement_name' => 'record_' . $priority);
  417. if ($line_num == 1 && $group_index == 1) {
  418. $options['prepare'] = TRUE;
  419. }
  420. }
  421. else {
  422. $options = array();
  423. }
  424. // Skip tripal_core_chado_insert() built-in validation?
  425. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  426. $options['skip_validation'] = TRUE;
  427. }
  428. $record = tripal_core_chado_insert($table, $values, $options);
  429. if (!$record) {
  430. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
  431. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  432. print "ERROR: " . $msg . "\n";
  433. $data[$priority]['error'] = TRUE;
  434. $no_errors = FALSE;
  435. }
  436. else {
  437. //add changes back to values array
  438. $data[$priority]['values_array'] = $record;
  439. $values = $record;
  440. // if mode=insert_once then ensure we only insert it once
  441. if (preg_match('/insert_once/', $table_data['mode'])) {
  442. $default_data[$priority]['inserted'] = TRUE;
  443. }
  444. // add to tripal_bulk_loader_inserted
  445. $insert_record = db_fetch_object(db_query(
  446. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  447. $table,
  448. $nid
  449. ));
  450. if ($insert_record) {
  451. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  452. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  453. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  454. return $no_errors;
  455. }
  456. else {
  457. $insert_record = array(
  458. 'nid' => $nid,
  459. 'table_inserted_into' => $table,
  460. 'table_primary_key' => $table_desc['primary key'][0],
  461. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  462. );
  463. //print 'New: '.print_r($insert_record,TRUE)."\n";
  464. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  465. return $no_errors;
  466. }//end of if insert record
  467. } //end of if insert was successful
  468. }
  469. else {
  470. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  471. if (!$exists) {
  472. // No record on select
  473. $msg = 'Line ' . $line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  474. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  475. $data[$priority]['error'] = TRUE;
  476. $no_errors = FALSE;
  477. }
  478. }
  479. return $no_errors;
  480. }
  481. /**
  482. * This function adds the file data to the values array
  483. *
  484. * @param $values
  485. * The default values array -contains all constants
  486. * @param $line
  487. * An array of values for the current line
  488. * @param $field2column
  489. * An array mapping values fields to line columns
  490. * @return
  491. * Supplemented values array
  492. */
  493. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  494. foreach ($values as $field => $value) {
  495. if (is_array($value)) {
  496. continue;
  497. }
  498. $column = $field2column[$field] - 1;
  499. if ($column < 0) {
  500. continue;
  501. }
  502. if (preg_match('/\S+/', $line[$column])) {
  503. $values[$field] = $line[$column];
  504. }
  505. else {
  506. unset($values[$field]);
  507. }
  508. }
  509. return $values;
  510. }
  511. /**
  512. * Handles foreign keys in the values array.
  513. *
  514. * Specifically, if the value for a field is an array then it is assumed that the array contains
  515. * the name of the record whose values array should be substituted here. Thus the foreign
  516. * record is looked up and the values array is substituted in.
  517. *
  518. */
  519. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  520. foreach ($values as $field => $value) {
  521. if (is_array($value)) {
  522. $foreign_record = $value['foreign record'];
  523. $foreign_priority = $record2priority[$foreign_record];
  524. $foreign_values = $data[$foreign_priority]['values_array'];
  525. // add to current values array
  526. $values[$field] = $foreign_values;
  527. }
  528. }
  529. return $values;
  530. }
  531. /**
  532. * Uses a supplied regex to transform spreadsheet values
  533. *
  534. * @param $values
  535. * The select/insert values array for the given table
  536. * @param $table_data
  537. * The data array for the given table
  538. */
  539. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  540. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
  541. return $values;
  542. }
  543. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  544. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  545. if (!is_array($regex_array['replace'])) {
  546. continue;
  547. }
  548. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  549. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  550. //print 'Was:'.$values[$field]."\n";
  551. // Check for <#column:\d+#> notation
  552. // if present replace with that column in the current line
  553. foreach ($regex_array['replace'] as $key => $replace) {
  554. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  555. foreach ($matches[1] as $k => $column_num) {
  556. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  557. }
  558. $regex_array['replace'][$key] = $replace;
  559. }
  560. }
  561. // do the full replacement
  562. $old_value = $values[$field];
  563. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  564. $values[$field] = $new_value;
  565. if ($values[$field] === '') {
  566. unset($values[$field]);
  567. }
  568. //print 'Now:'.$values[$field]."\n";
  569. }
  570. return $values;
  571. }
  572. /**
  573. * Flattens an array up to two levels
  574. * Used for printing of arrays without taking up much space
  575. */
  576. function tripal_bulk_loader_flatten_array($values) {
  577. $flattened_values = array();
  578. foreach ($values as $k => $v) {
  579. if (is_array($v)) {
  580. $vstr = array();
  581. foreach ($v as $vk => $vv) {
  582. if (drupal_strlen($vv) > 20) {
  583. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  584. }
  585. else {
  586. $vstr[] = $vk . '=>' . $vv;
  587. }
  588. }
  589. $v = '{' . implode(',', $vstr) . '}';
  590. }
  591. elseif (drupal_strlen($v) > 20) {
  592. $v = drupal_substr($v, 0, 20) . '...';
  593. }
  594. $flattened_values[] = $k . '=>' . $v;
  595. }
  596. return implode(', ', $flattened_values);
  597. }
  598. /**
  599. * Used to display loader progress to the user
  600. */
  601. function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
  602. // First iteration
  603. if($current == 0) {
  604. $new_bar = TRUE;
  605. fputs(STDOUT,"Progress:\n");
  606. }
  607. //Percentage round off for a more clean, consistent look
  608. $perc = round(($current/$total)*100,2);
  609. // percent indicator must be four characters, if shorter, add some spaces
  610. for($i=strlen($perc); $i<=4; $i++) {
  611. $perc = ' '.$perc;
  612. }
  613. $total_size = $size + $i + 3 + 2;
  614. // if it's not first go, remove the previous bar
  615. if(!$new_bar) {
  616. for($place = $total_size; $place > 0; $place--) {
  617. // echo a backspace (hex:08) to remove the previous character
  618. echo "\x08";
  619. }
  620. }
  621. // output the progess bar as it should be
  622. // Start with a border
  623. echo '[';
  624. for($place = 0; $place <= $size; $place++) {
  625. // output "full" spaces if this portion is completed
  626. if($place <= ($current / $total * $size)) {
  627. echo '|';
  628. }
  629. else {
  630. // Otherwise empty space
  631. echo '-';
  632. }
  633. }
  634. // End with a border
  635. echo ']';
  636. // end a bar with a percent indicator
  637. echo " $perc%";
  638. // if it's the end, add a new line
  639. if($current == $total) {
  640. echo "\n";
  641. }
  642. }