tripal_bulk_loader.loader.inc 38 KB

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