tripal_bulk_loader.loader.inc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. if ($table_data['need_further_processing']) {
  383. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $addt->line, $addt->field2column[$priority]);
  384. if (!$values) {
  385. //watchdog('T_bulk_loader', 'Line ' . $addt->line_num . ' Data File Added:' . print_r($values, TRUE), array(), WATCHDOG_NOTICE);
  386. }
  387. $values = tripal_bulk_loader_add_foreignkey_to_values($values, $data, $addt->record2priority);
  388. if (!$values) {
  389. //watchdog('T_bulk_loader', 'Line ' . $addt->line_num . ' FK Added:<pre>' . print_r($values, TRUE) . print_r($data[$priority], TRUE) . '</pre>', array(), WATCHDOG_NOTICE);
  390. }
  391. }
  392. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $addt->line);
  393. if (!$values) {
  394. //watchdog('T_bulk_loader', 'Line ' . $addt->line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
  395. }
  396. // get the table description
  397. $table_desc = tripal_core_get_chado_table_schema($table);
  398. // for an insert, check that all database required fields are present in the values array
  399. // we check for 'optional' in the mode for backwards compatibility. The 'optional'
  400. // mode used to be a type of insert
  401. if (preg_match('/insert/', $table_data['mode']) or preg_match('/optional/', $table_data['mode'])) {
  402. // Check all db required fields are set
  403. $fields = $table_desc['fields'];
  404. foreach ($fields as $field => $def) {
  405. // a field is considered missing if it cannot be null and there is no default
  406. // value for it or it is not of type 'serial'
  407. if ($def['not null'] == 1 and
  408. !array_key_exists($field, $values) and
  409. !isset($def['default']) and
  410. strcmp($def['type'], serial) != 0) {
  411. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  412. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_NOTICE);
  413. $data[$priority]['error'] = TRUE;
  414. }
  415. }
  416. }
  417. // Check that template required fields are present. if a required field is
  418. // missing and this
  419. // is an optional record then just return. otherwise raise an error
  420. $skip_optional = 0;
  421. foreach ($table_data['required'] as $field => $required) {
  422. if ($required) {
  423. // check if the field has no value (or array is empty)
  424. if (!isset($values[$field]) or (is_array($values[$field]) and count($values[$field]) == 0)){
  425. // check if the record is optional. For backwards compatiblity we need to
  426. // check if the 'mode' is set to 'optional'
  427. if ($table_data['optional'] or preg_match('/optional/', $table_data['mode'])) {
  428. $skip_optional = 1;
  429. // set the values array to be empty since we all required fields are
  430. // optional and we can't do a select/insert so we don't want to keep
  431. // the values if this record is used in a later FK relationship.
  432. $values = array();
  433. }
  434. else {
  435. $msg = "\nLine " . $addt->line_num . ' "' . $table_data['record_id'] .
  436. '" (' . $table_data['mode'] . ') Missing template required value: ' . $table . '.' . $field;
  437. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  438. $data[$priority]['error'] = TRUE;
  439. $no_errors = FALSE;
  440. }
  441. }
  442. }
  443. }
  444. // add new values array into the data array
  445. $data[$priority]['values_array'] = $values;
  446. // if there was an error already -> don't insert
  447. if ($data[$priority]['error']) {
  448. return $no_errors;
  449. }
  450. // skip optional fields
  451. if ($skip_optional) {
  452. return $no_errors;
  453. }
  454. // check if it is already inserted
  455. if ($table_data['inserted']) {
  456. //watchdog('T_bulk_loader','Already Inserted:'.print_r($values,TRUE),array(),WATCHDOG_NOTICE);
  457. return $no_errors;
  458. }
  459. $header = '';
  460. if (isset($values['feature_id'])) {
  461. $header = $values['feature_id']['uniquename'] . ' ' . $table_data['record_id'];
  462. }
  463. else {
  464. $header = $values['uniquename'] . ' ' . $table_data['record_id'];
  465. }
  466. // if "select if duplicate" is enabled then check to ensure unique constraint is not violoated.
  467. // If it is violoated then simply return, the record already exists in the database.
  468. // We check for insert_unique for backwards compatibilty but that mode no longer exists
  469. if (preg_match('/insert_unique/', $table_data['mode']) or
  470. $table_data['select_if_duplicate'] == 1) {
  471. $unique = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  472. //print 'Unique?'.print_r(array('table' => $table, 'columns' => array_keys($table_desc['fields']), 'values' => $values),TRUE).' returns '.$unique."\n";
  473. if ($unique > 0) {
  474. //$default_data[$priority]['inserted'] = TRUE;
  475. //watchdog('T_bulk_loader', $header.': Not unique ('.$unique.'):'.print_r($values,'values')."\n".print_r($data,TRUE),array(),WATCHDOG_NOTICE);;
  476. return $no_errors;
  477. }
  478. }
  479. if (!preg_match('/select/', $table_data['mode'])) {
  480. // Use prepared statement?
  481. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  482. $options = array('statement_name' => 'record_' . $addt->nid . '_' . $priority);
  483. if (($addt->line_num > 1 && $addt->group_index == 1) OR $addt->group_index > 1) {
  484. //$options['is_prepared'] = TRUE;
  485. }
  486. }
  487. else {
  488. $options = array();
  489. }
  490. // Skip tripal_core_chado_insert() built-in validation?
  491. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  492. $options['skip_validation'] = TRUE;
  493. }
  494. $record = tripal_core_chado_insert($table, $values, $options);
  495. if (!$record) {
  496. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
  497. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  498. print "ERROR: " . $msg . "\n";
  499. $data[$priority]['error'] = TRUE;
  500. $no_errors = FALSE;
  501. }
  502. else {
  503. //add changes back to values array
  504. $data[$priority]['values_array'] = $record;
  505. $values = $record;
  506. // if mode=insert_once then ensure we only insert it once
  507. if (preg_match('/insert_once/', $table_data['mode'])) {
  508. $default_data[$priority]['inserted'] = TRUE;
  509. }
  510. // add to tripal_bulk_loader_inserted
  511. if ($addt->node->keep_track_inserted) {
  512. $insert_record = db_fetch_object(db_query(
  513. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  514. $table,
  515. $addt->nid
  516. ));
  517. if ($insert_record) {
  518. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  519. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  520. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  521. return $no_errors;
  522. }
  523. else {
  524. $insert_record = array(
  525. 'nid' => $addt->nid,
  526. 'table_inserted_into' => $table,
  527. 'table_primary_key' => $table_desc['primary key'][0],
  528. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  529. );
  530. //print 'New: '.print_r($insert_record,TRUE)."\n";
  531. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  532. return $no_errors;
  533. }//end of if insert record
  534. }// end of if keeping track of records inserted
  535. } //end of if insert was successful
  536. }
  537. else {
  538. $exists = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, array('has_record' => TRUE));
  539. // if the record doesn't exists and it's not optional then generate an error
  540. if (!$exists and $table_data['optional'] != 1) {
  541. // No record on select
  542. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  543. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  544. $data[$priority]['error'] = TRUE;
  545. $no_errors = FALSE;
  546. }
  547. }
  548. return $no_errors;
  549. }
  550. /**
  551. * This function adds the file data to the values array
  552. *
  553. * @param $values
  554. * The default values array -contains all constants
  555. * @param $line
  556. * An array of values for the current line
  557. * @param $field2column
  558. * An array mapping values fields to line columns
  559. * @return
  560. * Supplemented values array
  561. */
  562. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  563. foreach ($values as $field => $value) {
  564. if (is_array($value)) {
  565. continue;
  566. }
  567. $column = $field2column[$field] - 1;
  568. if ($column < 0) {
  569. continue;
  570. }
  571. if (preg_match('/\S+/', $line[$column])) {
  572. $values[$field] = $line[$column];
  573. }
  574. else {
  575. unset($values[$field]);
  576. }
  577. }
  578. return $values;
  579. }
  580. /**
  581. * Handles foreign keys in the values array.
  582. *
  583. * Specifically, if the value for a field is an array then it is assumed that the array contains
  584. * the name of the record whose values array should be substituted here. Thus the foreign
  585. * record is looked up and the values array is substituted in.
  586. *
  587. */
  588. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  589. foreach ($values as $field => $value) {
  590. // if the field value is an array then it is an FK
  591. if (is_array($value)) {
  592. // get the name of the foreign record
  593. $foreign_record = $value['foreign record'];
  594. // get the corresponding priority of the foreign record
  595. $foreign_priority = $record2priority[$foreign_record];
  596. // get the values of the foreign record
  597. $foreign_values = $data[$foreign_priority]['values_array'];
  598. // substitue the foreign values for this fields values
  599. $values[$field] = $foreign_values;
  600. }
  601. }
  602. // return the updated field values
  603. return $values;
  604. }
  605. /**
  606. * Uses a supplied regex to transform spreadsheet values
  607. *
  608. * @param $values
  609. * The select/insert values array for the given table
  610. * @param $table_data
  611. * The data array for the given table
  612. */
  613. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  614. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
  615. return $values;
  616. }
  617. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  618. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  619. if (!is_array($regex_array['replace'])) {
  620. continue;
  621. }
  622. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  623. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  624. //print 'Was:'.$values[$field]."\n";
  625. // Check for <#column:\d+#> notation
  626. // if present replace with that column in the current line
  627. foreach ($regex_array['replace'] as $key => $replace) {
  628. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  629. foreach ($matches[1] as $k => $column_num) {
  630. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  631. }
  632. $regex_array['replace'][$key] = $replace;
  633. }
  634. }
  635. // do the full replacement
  636. $old_value = $values[$field];
  637. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  638. $values[$field] = $new_value;
  639. if ($values[$field] === '') {
  640. unset($values[$field]);
  641. }
  642. //print 'Now:'.$values[$field]."\n";
  643. }
  644. return $values;
  645. }
  646. /**
  647. * Flattens an array up to two levels
  648. * Used for printing of arrays without taking up much space
  649. */
  650. function tripal_bulk_loader_flatten_array($values) {
  651. $flattened_values = array();
  652. foreach ($values as $k => $v) {
  653. if (is_array($v)) {
  654. $vstr = array();
  655. foreach ($v as $vk => $vv) {
  656. if (drupal_strlen($vv) > 20) {
  657. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  658. }
  659. else {
  660. $vstr[] = $vk . '=>' . $vv;
  661. }
  662. }
  663. $v = '{' . implode(',', $vstr) . '}';
  664. }
  665. elseif (drupal_strlen($v) > 20) {
  666. $v = drupal_substr($v, 0, 20) . '...';
  667. }
  668. $flattened_values[] = $k . '=>' . $v;
  669. }
  670. return implode(', ', $flattened_values);
  671. }
  672. /**
  673. * Used to display loader progress to the user
  674. */
  675. function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
  676. // First iteration
  677. if ($current == 0) {
  678. $new_bar = TRUE;
  679. fputs(STDOUT, "Progress:\n");
  680. }
  681. //Percentage round off for a more clean, consistent look
  682. $perc = sprintf("%.02f",round(($current/$total)*100, 2));
  683. // percent indicator must be four characters, if shorter, add some spaces
  684. for ($i = strlen($perc); $i <= 4; $i++) {
  685. $perc = ' ' . $perc;
  686. }
  687. $total_size = $size + $i + 3 + 2;
  688. // if it's not first go, remove the previous bar
  689. if (!$new_bar) {
  690. for ($place = $total_size; $place > 0; $place--) {
  691. // echo a backspace (hex:08) to remove the previous character
  692. echo "\x08";
  693. }
  694. }
  695. // output the progess bar as it should be
  696. // Start with a border
  697. echo '[';
  698. for ($place = 0; $place <= $size; $place++) {
  699. // output "full" spaces if this portion is completed
  700. if ($place <= ($current / $total * $size)) {
  701. echo '|';
  702. }
  703. else {
  704. // Otherwise empty space
  705. echo '-';
  706. }
  707. }
  708. // End with a border
  709. echo ']';
  710. // end a bar with a percent indicator
  711. echo " $perc%";
  712. // if it's the end, add a new line
  713. if ($current == $total) {
  714. echo "\n";
  715. }
  716. }
  717. /**
  718. * Keep track of progress in file rather then database
  719. *
  720. * This provides an alternative method to keep track of progress that doesn't require the
  721. * database. It was needed because you can't switch databases within a transaction...
  722. * Waiting until the end of a constant set is much too long to wait for any indication
  723. * that things are working.
  724. *
  725. * Each line represents a line processed in the loading file. Each period (.) represents
  726. * a successfully inserted record.
  727. *
  728. * @param $job_id
  729. * The ID of the current tripal job
  730. * @param $record_added
  731. * A boolean indicated whether a record was added successfully
  732. * @param $line_complete
  733. * A boolean indicating whether the current line is finished
  734. * @param $close
  735. * A boolean indicating that the file should be closed
  736. */
  737. function tripal_bulk_loader_progress_file_track_job($job_id, $record_added, $line_complete = FALSE, $close = FALSE) {
  738. // retrieve the file handle
  739. $file_handle = variable_get('tripal_bulk_loader_progress_file_handle', NULL);
  740. // open file for reading if not already
  741. if (!$file_handle) {
  742. $file_handle = fopen('/tmp/tripal_bulk_loader_progress-'. $job_id . '.out', 'w');
  743. variable_set('tripal_bulk_loader_progress_file_handle', $file_handle);
  744. }
  745. if ($record_added) {
  746. fwrite($file_handle, '.');
  747. }
  748. if ($line_complete) {
  749. fwrite($file_handle, "\n");
  750. }
  751. // close the file if finished
  752. if ($close) {
  753. fclose($file_handle);
  754. variable_set('tripal_bulk_loader_progress_file_handle', NULL);
  755. }
  756. }