tripal_bulk_loader.loader.inc 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. foreach($duplicate[0] as $key => $value){
  485. $data[$priority]['values_array'] = $value;
  486. }
  487. }
  488. // if we have multiple fields returned then we need to set the values
  489. // the new array.
  490. else {
  491. // convert object to array
  492. $new_values = array();
  493. foreach($duplicate[0] as $key => $value){
  494. $new_values[$key] = $value;
  495. }
  496. $data[$priority]['values_array'] = $new_values;
  497. }
  498. // reset values in data array
  499. return $no_errors;
  500. }
  501. }
  502. if (!preg_match('/select/', $table_data['mode'])) {
  503. // Use prepared statement?
  504. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  505. $options = array('statement_name' => 'record_' . $addt->nid . '_' . $priority);
  506. if (($addt->line_num > 1 && $addt->group_index == 1) OR $addt->group_index > 1) {
  507. //$options['is_prepared'] = TRUE;
  508. }
  509. }
  510. else {
  511. $options = array();
  512. }
  513. // Skip tripal_core_chado_insert() built-in validation?
  514. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  515. $options['skip_validation'] = TRUE;
  516. }
  517. if ($table_data['update_if_duplicate'] == 1) {
  518. // TODO: handle updates
  519. //$record = tripal_core_chado_update($table, $values, $options);
  520. }
  521. else {
  522. $record = tripal_core_chado_insert($table, $values, $options);
  523. }
  524. if (!$record) {
  525. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Unable to insert record into ' . $table . ' where values:' . print_r($values, TRUE);
  526. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  527. print "ERROR: " . $msg . "\n";
  528. $data[$priority]['error'] = TRUE;
  529. $no_errors = FALSE;
  530. }
  531. else {
  532. // if mode=insert_once then ensure we only insert it once
  533. if (preg_match('/insert_once/', $table_data['mode'])) {
  534. $default_data[$priority]['inserted'] = TRUE;
  535. }
  536. // add to tripal_bulk_loader_inserted
  537. if ($addt->node->keep_track_inserted) {
  538. $insert_record = db_fetch_object(db_query(
  539. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  540. $table,
  541. $addt->nid
  542. ));
  543. if ($insert_record) {
  544. $insert_record->ids_inserted .= ',' . $values[ $table_desc['primary key'][0] ];
  545. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  546. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  547. return $no_errors;
  548. }
  549. else {
  550. $insert_record = array(
  551. 'nid' => $addt->nid,
  552. 'table_inserted_into' => $table,
  553. 'table_primary_key' => $table_desc['primary key'][0],
  554. 'ids_inserted' => $values[ $table_desc['primary key'][0] ],
  555. );
  556. //print 'New: '.print_r($insert_record,TRUE)."\n";
  557. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  558. return $no_errors;
  559. }//end of if insert record
  560. }// end of if keeping track of records inserted
  561. // substitute the values array for the primary key if it exists
  562. // and is a single field
  563. if(array_key_exists('primary key',$table_desc)){
  564. if(count($table_desc['primary key']) == 1){
  565. $pkey_field = $table_desc['primary key'][0];
  566. $data[$priority]['values_array'] = $record[$pkey_field];
  567. }
  568. } else {
  569. //add changes back to values array
  570. $data[$priority]['values_array'] = $record;
  571. $values = $record;
  572. }
  573. } //end of if insert was successful
  574. }
  575. else {
  576. // get the matches for this select
  577. $matches = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values);
  578. // if the record doesn't exists and it's not optional then generate an error
  579. if (count($matches) == 0){
  580. // No record on select
  581. if ($table_data['select_optional'] != 1) {
  582. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  583. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  584. $data[$priority]['error'] = TRUE;
  585. $no_errors = FALSE;
  586. }
  587. // there is no match and select optional is turned on, so we want to set
  588. // the values to empty for any records with an FK relationship on this one
  589. else {
  590. $data[$priority]['values_array'] = NULL;
  591. }
  592. }
  593. // if we have more than one record matching then this isn't good. We have to error out.
  594. if(count($matches) > 1){
  595. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Too many matching records in ' . $table . ' where values:' . print_r($values, TRUE);
  596. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  597. $data[$priority]['error'] = TRUE;
  598. $no_errors = FALSE;
  599. }
  600. }
  601. return $no_errors;
  602. }
  603. /**
  604. * This function adds the file data to the values array
  605. *
  606. * @param $values
  607. * The default values array -contains all constants
  608. * @param $line
  609. * An array of values for the current line
  610. * @param $field2column
  611. * An array mapping values fields to line columns
  612. * @return
  613. * Supplemented values array
  614. */
  615. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  616. foreach ($values as $field => $value) {
  617. if (is_array($value)) {
  618. continue;
  619. }
  620. $column = $field2column[$field] - 1;
  621. if ($column < 0) {
  622. continue;
  623. }
  624. if (preg_match('/\S+/', $line[$column])) {
  625. $values[$field] = $line[$column];
  626. }
  627. else {
  628. unset($values[$field]);
  629. }
  630. }
  631. return $values;
  632. }
  633. /**
  634. * Handles foreign keys in the values array.
  635. *
  636. * Specifically, if the value for a field is an array then it is assumed that the array contains
  637. * the name of the record whose values array should be substituted here. Thus the foreign
  638. * record is looked up and the values array is substituted in.
  639. *
  640. */
  641. function tripal_bulk_loader_add_foreignkey_to_values($values, $data, $record2priority) {
  642. foreach ($values as $field => $value) {
  643. // if the field value is an array then it is an FK
  644. if (is_array($value)) {
  645. // get the name of the foreign record
  646. $foreign_record = $value['foreign record'];
  647. // get the corresponding priority of the foreign record
  648. $foreign_priority = $record2priority[$foreign_record];
  649. // get the values of the foreign record
  650. $foreign_values = $data[$foreign_priority]['values_array'];
  651. // substitue the foreign values for this fields values
  652. $values[$field] = $foreign_values;
  653. }
  654. }
  655. // return the updated field values
  656. return $values;
  657. }
  658. /**
  659. * Uses a supplied regex to transform spreadsheet values
  660. *
  661. * @param $values
  662. * The select/insert values array for the given table
  663. * @param $table_data
  664. * The data array for the given table
  665. */
  666. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  667. if (empty($table_data['regex_transform']) OR !is_array($table_data['regex_transform'])) {
  668. return $values;
  669. }
  670. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  671. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  672. if (!is_array($regex_array['replace'])) {
  673. continue;
  674. }
  675. //print 'Match:'.print_r($regex_array['pattern'],TRUE)."\n";
  676. //print 'Replace:'.print_r($regex_array['replace'],TRUE)."\n";
  677. //print 'Was:'.$values[$field]."\n";
  678. // Check for <#column:\d+#> notation
  679. // if present replace with that column in the current line
  680. foreach ($regex_array['replace'] as $key => $replace) {
  681. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  682. foreach ($matches[1] as $k => $column_num) {
  683. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  684. }
  685. $regex_array['replace'][$key] = $replace;
  686. }
  687. }
  688. // do the full replacement
  689. $old_value = $values[$field];
  690. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  691. $values[$field] = $new_value;
  692. if ($values[$field] === '') {
  693. unset($values[$field]);
  694. }
  695. //print 'Now:'.$values[$field]."\n";
  696. }
  697. return $values;
  698. }
  699. /**
  700. * Flattens an array up to two levels
  701. * Used for printing of arrays without taking up much space
  702. */
  703. function tripal_bulk_loader_flatten_array($values) {
  704. $flattened_values = array();
  705. foreach ($values as $k => $v) {
  706. if (is_array($v)) {
  707. $vstr = array();
  708. foreach ($v as $vk => $vv) {
  709. if (drupal_strlen($vv) > 20) {
  710. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  711. }
  712. else {
  713. $vstr[] = $vk . '=>' . $vv;
  714. }
  715. }
  716. $v = '{' . implode(',', $vstr) . '}';
  717. }
  718. elseif (drupal_strlen($v) > 20) {
  719. $v = drupal_substr($v, 0, 20) . '...';
  720. }
  721. $flattened_values[] = $k . '=>' . $v;
  722. }
  723. return implode(', ', $flattened_values);
  724. }
  725. /**
  726. * Used to display loader progress to the user
  727. */
  728. function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
  729. // First iteration
  730. if ($current == 0) {
  731. $new_bar = TRUE;
  732. fputs(STDOUT, "Progress:\n");
  733. }
  734. //Percentage round off for a more clean, consistent look
  735. $perc = sprintf("%.02f",round(($current/$total)*100, 2));
  736. // percent indicator must be four characters, if shorter, add some spaces
  737. for ($i = strlen($perc); $i <= 4; $i++) {
  738. $perc = ' ' . $perc;
  739. }
  740. $total_size = $size + $i + 3 + 2;
  741. // if it's not first go, remove the previous bar
  742. if (!$new_bar) {
  743. for ($place = $total_size; $place > 0; $place--) {
  744. // echo a backspace (hex:08) to remove the previous character
  745. echo "\x08";
  746. }
  747. }
  748. // output the progess bar as it should be
  749. // Start with a border
  750. echo '[';
  751. for ($place = 0; $place <= $size; $place++) {
  752. // output "full" spaces if this portion is completed
  753. if ($place <= ($current / $total * $size)) {
  754. echo '|';
  755. }
  756. else {
  757. // Otherwise empty space
  758. echo '-';
  759. }
  760. }
  761. // End with a border
  762. echo ']';
  763. // end a bar with a percent indicator
  764. echo " $perc%";
  765. // if it's the end, add a new line
  766. if ($current == $total) {
  767. echo "\n";
  768. }
  769. }
  770. /**
  771. * Keep track of progress in file rather then database
  772. *
  773. * This provides an alternative method to keep track of progress that doesn't require the
  774. * database. It was needed because you can't switch databases within a transaction...
  775. * Waiting until the end of a constant set is much too long to wait for any indication
  776. * that things are working.
  777. *
  778. * Each line represents a line processed in the loading file. Each period (.) represents
  779. * a successfully inserted record.
  780. *
  781. * @param $job_id
  782. * The ID of the current tripal job
  783. * @param $record_added
  784. * A boolean indicated whether a record was added successfully
  785. * @param $line_complete
  786. * A boolean indicating whether the current line is finished
  787. * @param $close
  788. * A boolean indicating that the file should be closed
  789. */
  790. function tripal_bulk_loader_progress_file_track_job($job_id, $record_added, $line_complete = FALSE, $close = FALSE) {
  791. // retrieve the file handle
  792. $file_handle = variable_get('tripal_bulk_loader_progress_file_handle', NULL);
  793. // open file for reading if not already
  794. if (!$file_handle) {
  795. $file_handle = fopen('/tmp/tripal_bulk_loader_progress-'. $job_id . '.out', 'w');
  796. variable_set('tripal_bulk_loader_progress_file_handle', $file_handle);
  797. }
  798. if ($record_added) {
  799. fwrite($file_handle, '.');
  800. }
  801. if ($line_complete) {
  802. fwrite($file_handle, "\n");
  803. }
  804. // close the file if finished
  805. if ($close) {
  806. fclose($file_handle);
  807. variable_set('tripal_bulk_loader_progress_file_handle', NULL);
  808. }
  809. }