tripal_bulk_loader.loader.inc.orig 27 KB

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