tripal_bulk_loader.loader.inc 25 KB

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