tripal_bulk_loader.loader.inc 34 KB

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