tripal_bulk_loader.loader.inc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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. // Prep Work ==================================================================================
  118. print "\nPreparing to load...\n";
  119. $loaded_without_errors = TRUE;
  120. // Generate default values array
  121. $default_data = array();
  122. $field2column = array();
  123. $record2priority = array();
  124. $tables = array();
  125. foreach ($node->template->template_array as $priority => $record_array) {
  126. if (!is_array($record_array)) {
  127. continue;
  128. }
  129. // Add tables being inserted into to a list to be treated differently
  130. // this is used to acquire locks on these tables
  131. if (preg_match('/insert/', $record_array['mode'])) {
  132. $tables[$record_array['table']] = $record_array['table'];
  133. }
  134. foreach ($record_array['fields'] as $field_index => $field_array) {
  135. $default_data[$priority]['table'] = $record_array['table'];
  136. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert';
  137. $default_data[$priority]['select_if_duplicate'] = ($record_array['select_if_duplicate']) ? $record_array['select_if_duplicate'] : 1;
  138. $default_data[$priority]['disabled'] = ($record_array['disable']) ? $record_array['disable'] : 0;
  139. $default_data[$priority]['optional'] = ($record_array['optional']) ? $record_array['optional'] : 0;
  140. $default_data[$priority]['record_id'] = $record_array['record_id'];
  141. $record2priority[$record_array['record_id']] = $priority;
  142. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  143. $one = $default_data[$priority];
  144. if (isset($field_array['regex'])) {
  145. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  146. }
  147. $two = $default_data[$priority];
  148. if (preg_match('/table field/', $field_array['type'])) {
  149. $default_data[$priority]['values_array'][$field_array['field']] = '';
  150. $default_data[$priority]['need_further_processing'] = TRUE;
  151. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  152. }
  153. elseif (preg_match('/constant/', $field_array['type'])) {
  154. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  155. }
  156. elseif (preg_match('/foreign key/', $field_array['type'])) {
  157. $default_data[$priority]['values_array'][$field_array['field']] = array();
  158. $default_data[$priority]['values_array'][$field_array['field']]['foreign record'] = $field_array['foreign key'];
  159. $default_data[$priority]['need_further_processing'] = TRUE;
  160. }
  161. else {
  162. print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
  163. }
  164. $three = $default_data[$priority];
  165. //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);
  166. } // end of foreach field
  167. //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  168. } //end of foreach record
  169. ///////////////////////////////////////////////
  170. // For each set of constants
  171. ///////////////////////////////////////////////
  172. print "Loading...\n";
  173. $original_default_data = $default_data;
  174. $group_index = 0;
  175. $total_num_groups = sizeof($node->constants);
  176. foreach ($node->constants as $group_id => $set) {
  177. // revert default data array for next set of constants
  178. $default_data = $original_default_data;
  179. $group_index++;
  180. // Add constants
  181. if (!empty($set)) {
  182. print "Constants:\n";
  183. foreach ($set as $priority => $record) {
  184. foreach ($record as $field_id => $field) {
  185. print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
  186. if ($default_data[$priority]['table'] == $field['chado_table']) {
  187. if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
  188. if (isset($field2column[$priority][$field['chado_field']])) {
  189. $field2column[$priority][$field['chado_field']] = $field['value'];
  190. }
  191. else {
  192. $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
  193. }
  194. }
  195. else {
  196. print "ERROR: Template has changed after constants were assigned!\n";
  197. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  198. exit(1);
  199. }
  200. }
  201. else {
  202. print "ERROR: Template has changed after constants were assigned!\n";
  203. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  204. exit(1);
  205. }
  206. }
  207. }
  208. }
  209. //print "Default Data:".print_r($default_data,TRUE)."\n";
  210. //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  211. //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
  212. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  213. // Parse File adding records as we go ========================================================
  214. print "\tPreparing to load the current constant set...\n";
  215. // Open File
  216. print "\t\tOpen File...\n";
  217. $file_handle = fopen($node->file, 'r');
  218. // Set defaults
  219. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  220. fgets($file_handle, 4096);
  221. }
  222. $num_records = 0;
  223. $num_lines = 0;
  224. $num_errors = 0;
  225. $interval = intval($total_lines * 0.01);
  226. if ($interval == 0) {
  227. $interval = 1;
  228. }
  229. // Start Transaction
  230. switch (variable_get('tripal_bulk_loader_transactions', 'row')) {
  231. case "none":
  232. break;
  233. case "all":
  234. print "\t\tStart Transaction...\n";
  235. tripal_db_start_transaction();
  236. $transactions = TRUE;
  237. $savepoint = "";
  238. break;
  239. case "row":
  240. print "\t\tStart Transaction...\n";
  241. tripal_db_start_transaction();
  242. $transactions = TRUE;
  243. $savepoint = "last_row_complete";
  244. break;
  245. }
  246. // Disable triggers
  247. $triggers_disabled = FALSE;
  248. if ($transactions AND variable_get('tripal_bulk_loader_disable_triggers', TRUE)) {
  249. print "\t\tDefer Constraints...\n";
  250. $triggers_disabled = TRUE;
  251. chado_query("SET CONSTRAINTS ALL DEFERRED");
  252. }
  253. // Acquire Locks
  254. if ($transactions) {
  255. print "\t\tAcquiring Table Locks...\n";
  256. $lockmode = variable_get('tripal_bulk_loader_lock', 'ROW EXCLUSIVE');
  257. foreach ($tables as $table) {
  258. print "\t\t\t$lockmode for $table\n";
  259. chado_query("LOCK TABLE %s IN %s MODE", $table, $lockmode);
  260. }
  261. }
  262. print "\tLoading the current constant set...\n";
  263. tripal_bulk_loader_progress_bar(0, $total_lines);
  264. while (!feof($file_handle)) {
  265. // Clear variables
  266. // Was added to fix memory leak
  267. unset($line); unset($raw_line);
  268. unset($data); unset($data_keys);
  269. unset($priority); unset($sql);
  270. unset($result);
  271. $raw_line = fgets($file_handle, 4096);
  272. $raw_line = trim($raw_line);
  273. if (empty($raw_line)) {
  274. continue;
  275. } // skips blank lines
  276. $line = explode("\t", $raw_line);
  277. $num_lines++;
  278. // update the job status every 1% of lines processed for the current group
  279. if ($node->job_id and $num_lines % $interval == 0) {
  280. // percentage of lines processed for the current group
  281. $group_progress = round(($num_lines / $total_lines) * 100);
  282. tripal_bulk_loader_progress_bar($num_lines, $total_lines);
  283. // percentage of lines processed for all groups
  284. // <previous group index> * 100 + <current group progress>
  285. // --------------------------------------------------------
  286. // <total number of groups>
  287. // For example, if you were in the third group of 3 constant sets
  288. // and had a group percentage of 50% then the job progress would be
  289. // (2*100 + 50%) / 3 = 250%/3 = 83%
  290. $job_progress = round(((($group_index - 1) * 100) + $group_progress) / $total_num_groups);
  291. tripal_job_set_progress($node->job_id, $job_progress);
  292. }
  293. $data = $default_data;
  294. $data_keys = array_keys($data);
  295. foreach ($data_keys as $priority) {
  296. $options = array(
  297. 'field2column' => $field2column,
  298. 'record2priority' => $record2priority,
  299. 'line' => $line,
  300. 'line_num' => $num_lines,
  301. 'group_index' => $group_index,
  302. 'node' => $node,
  303. 'nid' => $node->nid,
  304. );
  305. // execute all records that are not disabled
  306. if ($data[$priority]['disabled'] == 0) {
  307. $status = process_data_array_for_line($priority, $data, $default_data, $options);
  308. }
  309. else {
  310. // set status to true for skipped records
  311. $status = TRUE;
  312. }
  313. tripal_bulk_loader_progress_file_track_job($job_id, $status);
  314. if (!$status ) {
  315. // Encountered an error
  316. if ($transactions) {
  317. tripal_db_rollback_transaction($savepoint);
  318. }
  319. $failed = TRUE;
  320. break;
  321. }
  322. } // end of foreach table in default data array
  323. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, TRUE);
  324. if ($failed) {
  325. break;
  326. }
  327. else {
  328. // Row inserted successfully
  329. // Set savepoint if supplied
  330. if ($savepoint) {
  331. if ($num_lines == 1) {
  332. tripal_db_set_savepoint_transaction($savepoint);
  333. }
  334. else {
  335. // Tell it to remove the previous savepoint of the same name
  336. tripal_db_set_savepoint_transaction($savepoint, TRUE);
  337. }
  338. }
  339. }
  340. } //end of foreach line of file
  341. // END Transaction
  342. if ($transactions) {
  343. // end the transaction
  344. tripal_db_commit_transaction();
  345. }
  346. if ($failed) {
  347. $loaded_without_errors = FALSE;
  348. break;
  349. }
  350. tripal_bulk_loader_progress_bar($total_lines, $total_lines);
  351. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, FALSE, TRUE);
  352. } //end of foreach constant set
  353. // set the status of the job (in the node not the tripal jobs)
  354. if ($loaded_without_errors) {
  355. $status = 'Loading Completed Successfully';
  356. }
  357. else {
  358. $status = 'Errors Encountered';
  359. }
  360. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
  361. }
  362. /**
  363. *
  364. *
  365. $options = array(
  366. 'field2column' => $field2column,
  367. 'record2priority' => $record2priority,
  368. 'line' => $line,
  369. 'line_num' => $num_lines,
  370. 'group_index' => $group_index,
  371. 'node' => $node,
  372. 'nid' => $node->nid,
  373. );
  374. */
  375. function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
  376. $table_data = $data[$priority];
  377. $addt = (object) $addt;
  378. $no_errors = TRUE;
  379. $table = $table_data['table'];
  380. $values = $table_data['values_array'];
  381. //watchdog('T_bulk_loader','Original:<pre>'.print_r($table_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  382. //print 'default values:'.print_r($values,TRUE)."\n";
  383. if ($table_data['need_further_processing']) {
  384. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $addt->line, $addt->field2column[$priority]);
  385. if (!$values) {
  386. //watchdog('T_bulk_loader', 'Line ' . $addt->line_num . ' Data File Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  387. }
  388. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $addt->record2priority);
  389. if (!$values) {
  390. //watchdog('T_bulk_loader', 'Line ' . $addt->line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
  391. }
  392. }
  393. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $addt->line);
  394. if (!$values) {
  395. //watchdog('T_bulk_loader', 'Line ' . $addt->line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
  396. }
  397. // SPF: commented out 9/5/2012... It is possible a record has no values (it's optional). The
  398. // checks below I think negate the need for this check, so commented out.
  399. // if (!$values) {
  400. // $msg = 'Line ' . $addt->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);
  401. // watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  402. // print "ERROR: " . $msg . "\n";
  403. // $data[$priority]['error'] = TRUE;
  404. // $no_errors = FALSE;
  405. // }
  406. // get the table description
  407. $table_desc = tripal_core_get_chado_table_schema($table);
  408. // check that all database required fields are present if this is in an insert
  409. // we check for 'optional' in the mode for backwards compatibility. The 'optional'
  410. // mode used to be a type of insert
  411. if (preg_match('/insert/', $table_data['mode']) or preg_match('/optional/', $table_data['mode'])) {
  412. // Check all db required fields are set
  413. $fields = $table_desc['fields'];
  414. foreach ($fields as $field => $def) {
  415. // a field is considered missing if it cannot be null and there is no default
  416. // value for it or it is not of type 'serial'{
  417. if ($def['not null'] == 1 and
  418. !array_key_exists($field, $values) and
  419. !isset($def['default']) and
  420. strcmp($def['type'], serial) != 0) {
  421. $msg = 'Line ' . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  422. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  423. $data[$priority]['error'] = TRUE;
  424. }
  425. }
  426. }
  427. // Check required fields are present if a required field is missing and this
  428. // is an optional record then just return. otherwise raise an error
  429. foreach ($table_data['required'] as $field => $required) {
  430. if ($required) {
  431. // check if the field has no value (or array is empty)
  432. if (!isset($values[$field]) or (is_array($values[$field]) and count($values[$field]) == 0)){
  433. if ($table_data['optional']) {
  434. return $no_errors;
  435. }
  436. else {
  437. $msg = 'Line ' . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Template Required Value: ' . $table . '.' . $field;
  438. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  439. $data[$priority]['error'] = TRUE;
  440. $no_errors = FALSE;
  441. }
  442. }
  443. }
  444. }
  445. // add new values array into the data array
  446. $data[$priority]['values_array'] = $values;
  447. // check if it is already inserted
  448. if ($table_data['inserted']) {
  449. //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
  450. return $no_errors;
  451. }
  452. // if there was an error already -> don't insert
  453. if ($data[$priority]['error']) {
  454. return $no_errors;
  455. }
  456. $header = '';
  457. if (isset($values['feature_id'])) {
  458. $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
  459. }
  460. else {
  461. $header = $values['uniquename'] . ' ' . $table_data['record_id'];
  462. }
  463. // if "select if duplicate" is enabled then check to ensure unique constraint is not violoated.
  464. // If it is violoated then simply return, the record already exists in the database.
  465. // We check for insert_unique for backwards compatibilty but that mode no longer exists
  466. if (preg_match('/insert_unique/', $table_data['mode']) or
  467. $table_data['select_if_duplicate'] == 1) {
  468. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  469. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  470. if ($unique > 0) {
  471. //$default_data[$priority]['inserted'] = TRUE;
  472. //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
  473. return $no_errors;
  474. }
  475. }
  476. if (!preg_match('/select/', $table_data['mode'])) {
  477. // Use prepared statement?
  478. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  479. $options = array('statement_name' => 'record_' . $addt->nid . '_' . $priority);
  480. if (($addt->line_num > 1 && $addt->group_index == 1) OR $addt->group_index > 1) {
  481. //$options['is_prepared'] = TRUE;
  482. }
  483. }
  484. else {
  485. $options = array();
  486. }
  487. // Skip tripal_core_chado_insert() built-in validation?
  488. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  489. $options['skip_validation'] = TRUE;
  490. }
  491. $record = tripal_core_chado_insert($table, $values, $options);
  492. if (!$record) {
  493. $msg = 'Line ' . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
  494. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  495. print "ERROR: " . $msg . "\n";
  496. $data[$priority]['error'] = TRUE;
  497. $no_errors = FALSE;
  498. }
  499. else {
  500. //add changes back to values array
  501. $data[$priority]['values_array'] = $record;
  502. $values = $record;
  503. // if mode=insert_once then ensure we only insert it once
  504. if (preg_match('/insert_once/', $table_data['mode'])) {
  505. $default_data[$priority]['inserted'] = TRUE;
  506. }
  507. // add to tripal_bulk_loader_inserted
  508. if ($addt->node->keep_track_inserted) {
  509. $insert_record = db_fetch_object(db_query(
  510. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  511. $table,
  512. $addt->nid
  513. ));
  514. if ($insert_record) {
  515. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  516. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  517. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  518. return $no_errors;
  519. }
  520. else {
  521. $insert_record = array(
  522. 'nid' => $addt->nid,
  523. 'table_inserted_into' => $table,
  524. 'table_primary_key' => $table_desc['primary key'][0],
  525. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  526. );
  527. //print 'New: '.print_r($insert_record,TRUE)."\n";
  528. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  529. return $no_errors;
  530. }//end of if insert record
  531. }// end of if keeping track of records inserted
  532. } //end of if insert was successful
  533. }
  534. else {
  535. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  536. // if the record doesn't exists and it's not optional then generate an error
  537. if (!$exists and $table_data['optional'] != 1) {
  538. // No record on select
  539. $msg = 'Line ' . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  540. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  541. $data[$priority]['error'] = TRUE;
  542. $no_errors = FALSE;
  543. }
  544. }
  545. return $no_errors;
  546. }
  547. /**
  548. * This function adds the file data to the values array
  549. *
  550. * @param $values
  551. * The default values array -contains all constants
  552. * @param $line
  553. * An array of values for the current line
  554. * @param $field2column
  555. * An array mapping values fields to line columns
  556. * @return
  557. * Supplemented values array
  558. */
  559. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  560. foreach ($values as $field => $value) {
  561. if (is_array($value)) {
  562. continue;
  563. }
  564. $column = $field2column[$field] - 1;
  565. if ($column < 0) {
  566. continue;
  567. }
  568. if (preg_match('/\S+/', $line[$column])) {
  569. $values[$field] = $line[$column];
  570. }
  571. else {
  572. unset($values[$field]);
  573. }
  574. }
  575. return $values;
  576. }
  577. /**
  578. * Handles foreign keys in the values array.
  579. *
  580. * Specifically, if the value for a field is an array then it is assumed that the array contains
  581. * the name of the record whose values array should be substituted here. Thus the foreign
  582. * record is looked up and the values array is substituted in.
  583. *
  584. */
  585. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  586. foreach ($values as $field => $value) {
  587. if (is_array($value)) {
  588. $foreign_record = $value['foreign record'];
  589. $foreign_priority = $record2priority[$foreign_record];
  590. $foreign_values = $data[$foreign_priority]['values_array'];
  591. // add to current values array
  592. $values[$field] = $foreign_values;
  593. }
  594. }
  595. return $values;
  596. }
  597. /**
  598. * Uses a supplied regex to transform spreadsheet values
  599. *
  600. * @param $values
  601. * The select/insert values array for the given table
  602. * @param $table_data
  603. * The data array for the given table
  604. */
  605. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  606. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
  607. return $values;
  608. }
  609. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  610. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  611. if (!is_array($regex_array['replace'])) {
  612. continue;
  613. }
  614. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  615. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  616. //print 'Was:'.$values[$field]."\n";
  617. // Check for <#column:\d+#> notation
  618. // if present replace with that column in the current line
  619. foreach ($regex_array['replace'] as $key => $replace) {
  620. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  621. foreach ($matches[1] as $k => $column_num) {
  622. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  623. }
  624. $regex_array['replace'][$key] = $replace;
  625. }
  626. }
  627. // do the full replacement
  628. $old_value = $values[$field];
  629. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  630. $values[$field] = $new_value;
  631. if ($values[$field] === '') {
  632. unset($values[$field]);
  633. }
  634. //print 'Now:'.$values[$field]."\n";
  635. }
  636. return $values;
  637. }
  638. /**
  639. * Flattens an array up to two levels
  640. * Used for printing of arrays without taking up much space
  641. */
  642. function tripal_bulk_loader_flatten_array($values) {
  643. $flattened_values = array();
  644. foreach ($values as $k => $v) {
  645. if (is_array($v)) {
  646. $vstr = array();
  647. foreach ($v as $vk => $vv) {
  648. if (drupal_strlen($vv) > 20) {
  649. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  650. }
  651. else {
  652. $vstr[] = $vk . '=>' . $vv;
  653. }
  654. }
  655. $v = '{' . implode(',', $vstr) . '}';
  656. }
  657. elseif (drupal_strlen($v) > 20) {
  658. $v = drupal_substr($v, 0, 20) . '...';
  659. }
  660. $flattened_values[] = $k . '=>' . $v;
  661. }
  662. return implode(', ', $flattened_values);
  663. }
  664. /**
  665. * Used to display loader progress to the user
  666. */
  667. function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
  668. // First iteration
  669. if ($current == 0) {
  670. $new_bar = TRUE;
  671. fputs(STDOUT, "Progress:\n");
  672. }
  673. //Percentage round off for a more clean, consistent look
  674. $perc = sprintf("%.02f",round(($current/$total)*100, 2));
  675. // percent indicator must be four characters, if shorter, add some spaces
  676. for ($i = strlen($perc); $i <= 4; $i++) {
  677. $perc = ' ' . $perc;
  678. }
  679. $total_size = $size + $i + 3 + 2;
  680. // if it's not first go, remove the previous bar
  681. if (!$new_bar) {
  682. for ($place = $total_size; $place > 0; $place--) {
  683. // echo a backspace (hex:08) to remove the previous character
  684. echo "\x08";
  685. }
  686. }
  687. // output the progess bar as it should be
  688. // Start with a border
  689. echo '[';
  690. for ($place = 0; $place <= $size; $place++) {
  691. // output "full" spaces if this portion is completed
  692. if ($place <= ($current / $total * $size)) {
  693. echo '|';
  694. }
  695. else {
  696. // Otherwise empty space
  697. echo '-';
  698. }
  699. }
  700. // End with a border
  701. echo ']';
  702. // end a bar with a percent indicator
  703. echo " $perc%";
  704. // if it's the end, add a new line
  705. if ($current == $total) {
  706. echo "\n";
  707. }
  708. }
  709. /**
  710. * Keep track of progress in file rather then database
  711. *
  712. * This provides an alternative method to keep track of progress that doesn't require the
  713. * database. It was needed because you can't switch databases within a transaction...
  714. * Waiting until the end of a constant set is much too long to wait for any indication
  715. * that things are working.
  716. *
  717. * Each line represents a line processed in the loading file. Each period (.) represents
  718. * a successfully inserted record.
  719. *
  720. * @param $job_id
  721. * The ID of the current tripal job
  722. * @param $record_added
  723. * A boolean indicated whether a record was added successfully
  724. * @param $line_complete
  725. * A boolean indicating whether the current line is finished
  726. * @param $close
  727. * A boolean indicating that the file should be closed
  728. */
  729. function tripal_bulk_loader_progress_file_track_job($job_id, $record_added, $line_complete = FALSE, $close = FALSE) {
  730. // retrieve the file handle
  731. $file_handle = variable_get('tripal_bulk_loader_progress_file_handle', NULL);
  732. // open file for reading if not already
  733. if (!$file_handle) {
  734. $file_handle = fopen('/tmp/tripal_bulk_loader_progress-'. $job_id . '.out', 'w');
  735. variable_set('tripal_bulk_loader_progress_file_handle', $file_handle);
  736. }
  737. if ($record_added) {
  738. fwrite($file_handle, '.');
  739. }
  740. if ($line_complete) {
  741. fwrite($file_handle, "\n");
  742. }
  743. // close the file if finished
  744. if ($close) {
  745. fclose($file_handle);
  746. variable_set('tripal_bulk_loader_progress_file_handle', NULL);
  747. }
  748. }