tripal_bulk_loader.loader.inc 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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. * @ingroup tripal_bulk_loader
  13. */
  14. function tripal_bulk_loader_add_loader_job_form($form_state, $node) {
  15. $form = array();
  16. // --notify--
  17. if ($node->job_status == 'Loading...') {
  18. drupal_set_message(t("The Loading Summary only updates at the end of each constant set.
  19. Although records may have already been inserted, they won't be available until the
  20. current constant set is full loaded and no errors are encountered.", array()), 'warning');
  21. }
  22. $form['nid'] = array(
  23. '#type' => 'hidden',
  24. '#value' => $node->nid,
  25. );
  26. $form['file'] = array(
  27. '#type' => 'hidden',
  28. '#value' => $node->file
  29. );
  30. $form['job_id'] = array(
  31. '#type' => 'hidden',
  32. '#value' => $node->job_id,
  33. );
  34. $form['submit'] = array(
  35. '#type' => 'submit',
  36. '#value' => ($node->job_id) ? 'Re-Submit Job' : 'Submit Job',
  37. );
  38. $form['submit-cancel'] = array(
  39. '#type' => ($node->job_id)? 'submit' : 'hidden',
  40. '#value' => 'Cancel Job',
  41. );
  42. if ($node->keep_track_inserted) {
  43. $form['submit-revert'] = array(
  44. '#type' => ($node->job_id) ? 'submit' : 'hidden',
  45. '#value' => 'Revert',
  46. );
  47. }
  48. return $form;
  49. }
  50. /**
  51. * Add Loader Job Form (Submit)
  52. *
  53. * @ingroup tripal_bulk_loader
  54. */
  55. function tripal_bulk_loader_add_loader_job_form_submit($form, $form_state) {
  56. global $user;
  57. if (preg_match('/Submit Job/', $form_state['values']['op'])) {
  58. //Submit Tripal Job
  59. $job_args[1] = $form_state['values']['nid'];
  60. if (is_readable($form_state['values']['file'])) {
  61. $fname = basename($form_state['values']['file']);
  62. $job_id = tripal_add_job("Bulk Loading Job: $fname", 'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
  63. // add job_id to bulk_loader node
  64. $success = db_query("UPDATE {tripal_bulk_loader} SET job_id=%d WHERE nid=%d", $job_id, $form_state['values']['nid']);
  65. // change status
  66. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  67. }
  68. else {
  69. drupal_set_message(t("Can not open %file. Job not scheduled.", array('%file' => $form_state['values']['file'])));
  70. }
  71. }
  72. elseif (preg_match('/Re-Submit Job/', $form_state['values']['op'])) {
  73. tripal_jobs_rerun($form_state['values']['job_id']);
  74. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Submitted to Queue', $form_state['values']['nid']);
  75. }
  76. elseif (preg_match('/Cancel Job/', $form_state['values']['op'])) {
  77. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Job Cancelled', $form_state['values']['nid']);
  78. tripal_jobs_cancel($form_state['values']['job_id']);
  79. }
  80. elseif (preg_match('/Revert/', $form_state['values']['op'])) {
  81. // Remove the records from the database that were already inserted
  82. $resource = db_query('SELECT * FROM {tripal_bulk_loader_inserted} WHERE nid=%d ORDER BY tripal_bulk_loader_inserted_id DESC', $form_state['values']['nid']);
  83. while ($r = db_fetch_object($resource)) {
  84. $ids = preg_split('/,/', $r->ids_inserted);
  85. db_query('DELETE FROM {%s} WHERE %s IN (%s)', $r->table_inserted_into, $r->table_primary_key, $r->ids_inserted);
  86. $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));
  87. if (!$result->present) {
  88. drupal_set_message(t('Successfully Removed data Inserted into the %tableto table.', array('%tableto' => $r->table_inserted_into)));
  89. db_query('DELETE FROM {tripal_bulk_loader_inserted} WHERE tripal_bulk_loader_inserted_id=%d', $r->tripal_bulk_loader_inserted_id);
  90. }
  91. else {
  92. drupal_set_message(t('Unable to remove data Inserted into the %tableto table!', array('%tableto' => $r->table_inserted_into)), 'error');
  93. }
  94. }
  95. // reset status
  96. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Reverted -Data Deleted', $form_state['values']['nid']);
  97. }
  98. }
  99. /**
  100. * Tripal Bulk Loader
  101. *
  102. * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  103. *
  104. * @param $nid
  105. * The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  106. * in the node (ie: template ID and file)
  107. *
  108. * Note: Instead of returning a value this function updates the tripal_bulk_loader.status.
  109. * Errors are thrown through watchdog and can be viewed at admin/reports/dblog.
  110. *
  111. * @ingroup tripal_bulk_loader
  112. */
  113. function tripal_bulk_loader_load_data($nid, $job_id) {
  114. // ensure no timeout
  115. set_time_limit(0);
  116. // set the status of the job (in the node not the tripal jobs)
  117. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'Loading...', $nid);
  118. $node = node_load($nid);
  119. print "Template: " . $node->template->name . " (" . $node->template_id . ")\n";
  120. $total_lines = trim(`wc --lines < $node->file`);
  121. print "File: " . $node->file . " (" . $total_lines . " lines)\n";
  122. print "\nClearing all prepared statements from previous runs of this loader...\n";
  123. tripal_core_chado_clear_prepared('_'.$node->nid.'_');
  124. // Prep Work ==================================================================================
  125. print "\nPreparing to load...\n";
  126. $loaded_without_errors = TRUE;
  127. // Generate default values array
  128. $default_data = array();
  129. $field2column = array();
  130. $record2priority = array();
  131. $tables = array();
  132. $template_array = $node->template->template_array;
  133. // first build the record2priority array
  134. foreach ($template_array as $priority => $record_array) {
  135. $record2priority[$record_array['record_id']] = $priority;
  136. }
  137. //
  138. foreach ($template_array as $priority => $record_array) {
  139. if (!is_array($record_array)) {
  140. continue;
  141. }
  142. // Add tables being inserted into to a list to be treated differently
  143. // this is used to acquire locks on these tables
  144. if (preg_match('/insert/', $record_array['mode'])) {
  145. $tables[$record_array['table']] = $record_array['table'];
  146. }
  147. // iterate through each of the fiels for the current record and
  148. // set the default_data array
  149. foreach ($record_array['fields'] as $field_index => $field_array) {
  150. $default_data[$priority]['table'] = $record_array['table'];
  151. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert';
  152. $default_data[$priority]['select_if_duplicate'] = ($record_array['select_if_duplicate']) ? $record_array['select_if_duplicate'] : 0;
  153. $default_data[$priority]['update_if_duplicate'] = ($record_array['update_if_duplicate']) ? $record_array['update_if_duplicate'] : 0;
  154. $default_data[$priority]['disabled'] = ($record_array['disable']) ? $record_array['disable'] : 0;
  155. $default_data[$priority]['optional'] = ($record_array['optional']) ? $record_array['optional'] : 0;
  156. $default_data[$priority]['select_optional'] = ($record_array['select_optional']) ? $record_array['select_optional'] : 0;
  157. $default_data[$priority]['record_id'] = $record_array['record_id'];
  158. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  159. $one = $default_data[$priority];
  160. if (isset($field_array['regex'])) {
  161. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  162. }
  163. $two = $default_data[$priority];
  164. if (preg_match('/table field/', $field_array['type'])) {
  165. $default_data[$priority]['values_array'][$field_array['field']] = '';
  166. $default_data[$priority]['need_further_processing'] = TRUE;
  167. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  168. }
  169. elseif (preg_match('/constant/', $field_array['type'])) {
  170. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  171. }
  172. elseif (preg_match('/foreign key/', $field_array['type'])) {
  173. $default_data[$priority]['values_array'][$field_array['field']] = array();
  174. $default_data[$priority]['need_further_processing'] = TRUE;
  175. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['record'] = $field_array['foreign key'];
  176. // Add in the FK / Referral table
  177. $fk_priority = $record2priority[$field_array['foreign key']];
  178. $fk_table = $template_array[$fk_priority]['table'];
  179. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['table'] = $fk_table;
  180. // Add in the FK / Referral field
  181. // for backwards compatibility we need to get the FK relationship to find
  182. // out what field we're joining on. For templates created using a
  183. // previous version it was assumed that the FK field was always the field to join
  184. if (!array_key_exists('foreign field', $field_array)) {
  185. $tbl_description = tripal_core_get_chado_table_schema($record_array['table']);
  186. foreach ($tbl_description['foreign keys'] as $key_table => $key_array) {
  187. if ($key_table == $fk_table) {
  188. foreach ($key_array['columns'] as $left_field => $right_field) {
  189. if ($left_field == $field_array['field']) {
  190. $field_array['foreign field'] = $right_field;
  191. }
  192. }
  193. }
  194. }
  195. }
  196. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['field'] = $field_array['foreign field'];
  197. }
  198. else {
  199. print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
  200. }
  201. $three = $default_data[$priority];
  202. } // end of foreach field
  203. } //end of foreach record
  204. ///////////////////////////////////////////////
  205. // For each set of constants
  206. ///////////////////////////////////////////////
  207. print "Loading...\n";
  208. $original_default_data = $default_data;
  209. $group_index = 0;
  210. $total_num_groups = sizeof($node->constants);
  211. foreach ($node->constants as $group_id => $set) {
  212. // revert default data array for next set of constants
  213. $default_data = $original_default_data;
  214. $group_index++;
  215. // Add constants
  216. if (!empty($set)) {
  217. print "Constants:\n";
  218. foreach ($set as $priority => $record) {
  219. foreach ($record as $field_id => $field) {
  220. print "\t- " . $field['chado_table'] . '.' . $field['chado_field'] . ' = ' . $field['value'] . "\n";
  221. if ($default_data[$priority]['table'] == $field['chado_table']) {
  222. if (isset($default_data[$priority]['values_array'][$field['chado_field']])) {
  223. if (isset($field2column[$priority][$field['chado_field']])) {
  224. $field2column[$priority][$field['chado_field']] = $field['value'];
  225. }
  226. else {
  227. $default_data[$priority]['values_array'][$field['chado_field']] = $field['value'];
  228. }
  229. }
  230. else {
  231. print "ERROR: Template has changed after constants were assigned!\n";
  232. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  233. exit(1);
  234. }
  235. }
  236. else {
  237. print "ERROR: Template has changed after constants were assigned!\n";
  238. watchdog('T_bulk_loader', 'Template has changed after constants were assigned', array(), WATCHDOG_NOTICE);
  239. exit(1);
  240. }
  241. }
  242. }
  243. }
  244. // Open File
  245. print "\tPreparing to load the current constant set...\n";
  246. print "\t\tOpen File...\n";
  247. try {
  248. $file = new SplFileObject($node->file, 'r');
  249. }
  250. catch (Exception $e) {
  251. watchdog('T_bulk_loader', 'Could not open file %file',
  252. array($node->file), WATCHDOG_ERROR);
  253. return;
  254. }
  255. // Set defaults
  256. $header = '';
  257. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  258. $file->next();
  259. $header = $file->current();
  260. }
  261. $num_records = 0;
  262. $num_lines = 0;
  263. $num_errors = 0;
  264. $interval = intval($total_lines * 0.0001);
  265. if ($interval == 0) {
  266. $interval = 1;
  267. }
  268. // Start Transaction
  269. $savepoint = '';
  270. switch (variable_get('tripal_bulk_loader_transactions', 'row')) {
  271. case "none":
  272. break;
  273. case "all":
  274. print "\t\tStart Transaction...\n";
  275. tripal_db_start_transaction();
  276. $transactions = TRUE;
  277. $savepoint = "";
  278. break;
  279. case "row":
  280. print "\t\tStart Transaction...\n";
  281. tripal_db_start_transaction();
  282. $transactions = TRUE;
  283. $savepoint = "last_row_complete";
  284. break;
  285. }
  286. // Disable triggers
  287. $triggers_disabled = FALSE;
  288. if ($transactions AND variable_get('tripal_bulk_loader_disable_triggers', TRUE)) {
  289. print "\t\tDefer Constraints...\n";
  290. $triggers_disabled = TRUE;
  291. chado_query("SET CONSTRAINTS ALL DEFERRED");
  292. }
  293. // Acquire Locks
  294. if ($transactions) {
  295. print "\t\tAcquiring Table Locks...\n";
  296. $lockmode = variable_get('tripal_bulk_loader_lock', 'ROW EXCLUSIVE');
  297. foreach ($tables as $table) {
  298. print "\t\t\t$lockmode for $table\n";
  299. chado_query("LOCK TABLE %s IN %s MODE", $table, $lockmode);
  300. }
  301. }
  302. print "\tLoading the current constant set...\n";
  303. tripal_bulk_loader_progress_bar(0, $total_lines);
  304. while (!$file->eof()) {
  305. $file->next();
  306. $raw_line = $file->current();
  307. $raw_line = trim($raw_line);
  308. if (empty($raw_line)) {
  309. continue;
  310. } // skips blank lines
  311. $line = explode("\t", $raw_line);
  312. $num_lines++;
  313. // update the job status every 1% of lines processed for the current group
  314. if ($node->job_id and $num_lines % $interval == 0) {
  315. // percentage of lines processed for the current group
  316. $group_progress = round(($num_lines / $total_lines) * 100);
  317. tripal_bulk_loader_progress_bar($num_lines, $total_lines);
  318. // percentage of lines processed for all groups
  319. // <previous group index> * 100 + <current group progress>
  320. // --------------------------------------------------------
  321. // <total number of groups>
  322. // For example, if you were in the third group of 3 constant sets
  323. // and had a group percentage of 50% then the job progress would be
  324. // (2*100 + 50%) / 3 = 250%/3 = 83%
  325. $job_progress = round(((($group_index - 1) * 100) + $group_progress) / $total_num_groups);
  326. tripal_job_set_progress($node->job_id, $job_progress);
  327. }
  328. $data = $default_data;
  329. // iterate through each record and process the line
  330. $data_keys = array_keys($data);
  331. foreach ($data_keys as $priority) {
  332. $options = array(
  333. 'field2column' => $field2column,
  334. 'record2priority' => $record2priority,
  335. 'line' => $line,
  336. 'line_num' => $num_lines,
  337. 'group_index' => $group_index,
  338. 'node' => $node,
  339. 'nid' => $node->nid,
  340. );
  341. // execute all records that are not disabled
  342. $no_errors = FALSE;
  343. if (array_key_exists($priority, $data) and
  344. array_key_exists('disabled', $data[$priority]) and
  345. $data[$priority]['disabled'] == 0) {
  346. $no_errors = process_data_array_for_line($priority, $data, $default_data, $options);
  347. }
  348. else {
  349. // set status to true for skipped records
  350. $no_errors = TRUE;
  351. }
  352. tripal_bulk_loader_progress_file_track_job($job_id, $no_errors);
  353. $failed = FALSE;
  354. if ( !$no_errors ) {
  355. // Encountered an error
  356. if ($transactions) {
  357. tripal_db_rollback_transaction($savepoint);
  358. }
  359. $failed = TRUE;
  360. break;
  361. }
  362. } // end of foreach table in default data array
  363. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, TRUE);
  364. if ($failed) {
  365. break;
  366. }
  367. else {
  368. // Row inserted successfully
  369. // Set savepoint if supplied
  370. if ($savepoint) {
  371. if ($num_lines == 1) {
  372. tripal_db_set_savepoint_transaction($savepoint);
  373. }
  374. else {
  375. // Tell it to remove the previous savepoint of the same name
  376. tripal_db_set_savepoint_transaction($savepoint, TRUE);
  377. }
  378. }
  379. }
  380. } //end of foreach line of file
  381. // END Transaction
  382. if ($transactions) {
  383. // end the transaction
  384. tripal_db_commit_transaction();
  385. }
  386. if ($failed) {
  387. $loaded_without_errors = FALSE;
  388. break;
  389. }
  390. tripal_bulk_loader_progress_bar($total_lines, $total_lines);
  391. tripal_bulk_loader_progress_file_track_job($job_id, FALSE, FALSE, TRUE);
  392. } //end of foreach constant set
  393. // set the status of the job (in the node not the tripal jobs)
  394. if ($loaded_without_errors) {
  395. $status = 'Loading Completed Successfully';
  396. }
  397. else {
  398. $status = 'Errors Encountered';
  399. }
  400. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", $status, $nid);
  401. }
  402. /**
  403. * Process the data array for a given line
  404. *
  405. * @param $addt
  406. * Requires: field2column', 'record2priority', 'line', 'line_num',
  407. * 'group_index', 'node', 'nid'
  408. *
  409. * @ingroup tripal_bulk_loader
  410. */
  411. function process_data_array_for_line($priority, &$data, &$default_data, $addt) {
  412. //$time_start = microtime(true);
  413. $table_data = $data[$priority];
  414. $addt = (object) $addt;
  415. $no_errors = TRUE;
  416. $table = $table_data['table'];
  417. $values = $table_data['values_array'];
  418. // populate the values array with real value either from the input data file line
  419. // or from the foreign key / referral record
  420. if (array_key_exists('need_further_processing', $table_data) and $table_data['need_further_processing']) {
  421. if (array_key_exists($priority, $addt->field2column)) {
  422. $values = tripal_bulk_loader_add_spreadsheetdata_to_values($values, $addt->line, $addt->field2column[$priority]);
  423. }
  424. $values = tripal_bulk_loader_add_foreignkey_to_values($table_data, $values, $data, $addt->record2priority, $addt->nid, $priority, $default_data);
  425. }
  426. $values = tripal_bulk_loader_regex_tranform_values($values, $table_data, $addt->line);
  427. if (!$values) {
  428. //watchdog('T_bulk_loader', 'Line ' . $addt->line_num . ' Regex:<pre>' . print_r($values, TRUE) . print_r($table_data, TRUE) . '</pre>' . '</pre>', array(), WATCHDOG_NOTICE);
  429. }
  430. // get the table description
  431. $table_desc = tripal_core_get_chado_table_schema($table);
  432. if (!$table_desc) {
  433. watchdog('T_bulk_loader', "Failure: Tripal does not know about the table named '%table'. If this is a custom table,
  434. please define it first", array('%table' => $table), WATCHDOG_ERROR);
  435. $data[$priority]['error'] = TRUE;
  436. return;
  437. }
  438. // Check that template required fields are present. if a required field is
  439. // missing and this
  440. // is an optional record then just return. otherwise raise an error
  441. $skip_optional = 0;
  442. foreach ($table_data['required'] as $field => $required) {
  443. if ($required) {
  444. // check if the field has no value (or array is empty)
  445. if (!isset($values[$field]) or
  446. (is_array($values[$field]) and count($values[$field]) == 0)) {
  447. // check if the record is optional. For backwards compatiblity we need to
  448. // check if the 'mode' is set to 'optional'
  449. if ($table_data['optional'] or preg_match('/optional/', $table_data['mode']) or
  450. $table_data['select_optional']) {
  451. $skip_optional = 1;
  452. // set the values array to be empty since we all required fields are
  453. // optional and we can't do a select/insert so we don't want to keep
  454. // the values if this record is used in a later FK relationship.
  455. $values = array();
  456. }
  457. else {
  458. $msg = "\nLine " . $addt->line_num . ' "' . $table_data['record_id'] .
  459. '" (' . $table_data['mode'] . ') Missing template required value: ' . $table . '.' . $field;
  460. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  461. $data[$priority]['error'] = TRUE;
  462. $no_errors = FALSE;
  463. }
  464. }
  465. }
  466. }
  467. // for an insert, check that all database required fields are present in the values array
  468. // we check for 'optional' in the mode for backwards compatibility. The 'optional'
  469. // mode used to be a type of insert
  470. if (!$skip_optional and (preg_match('/insert/', $table_data['mode']) or
  471. preg_match('/optional/', $table_data['mode']))) {
  472. // Check all database table required fields are set
  473. $fields = $table_desc['fields'];
  474. foreach ($fields as $field => $def) {
  475. // a field is considered missing if it cannot be null and there is no default
  476. // value for it or it is not of type 'serial'
  477. if (array_key_exists('not null', $def) and $def['not null'] == 1 and // field must have a value
  478. !array_key_exists($field, $values) and // there is not a value for it
  479. !array_key_exists('default', $def) and // there is no default for it
  480. strcmp($def['type'], 'serial') != 0) { // it is not a 'serial' type column
  481. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] .
  482. ' (' . $table_data['mode'] . ') Missing Database Required Value: ' . $table . '.' . $field;
  483. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  484. $data[$priority]['error'] = TRUE;
  485. }
  486. }
  487. }
  488. // add updated values array into the data array
  489. $data[$priority]['values_array'] = $values;
  490. // if there was an error already -> don't insert
  491. if (array_key_exists('error', $data[$priority]) and $data[$priority]['error']) {
  492. watchdog('T_bulk_loader','Skipping processing of %table due to previous errors',array('%table'=>$table),WATCHDOG_NOTICE);
  493. return $no_errors;
  494. }
  495. // skip optional fields
  496. if ($skip_optional) {
  497. watchdog('T_bulk_loader','Skipping an optional record (%record)',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
  498. return $no_errors;
  499. }
  500. // check if it is already inserted
  501. if (array_key_exists('inserted', $table_data) and $table_data['inserted']) {
  502. watchdog('T_bulk_loader','Skipping %record since it is already inserted',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
  503. return $no_errors;
  504. }
  505. // check if it is already selected, if so, just get the value stored in
  506. // the default_data array
  507. if (array_key_exists('selected', $table_data) and $table_data['selected']) {
  508. $data[$priority]['values_array'] = $default_data[$priority]['values_array'];
  509. watchdog('T_bulk_loader','%record was already selected thus we are just returning the values previously selected.',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
  510. return $no_errors;
  511. }
  512. // make sure we have some value in the select_if_duplicate and update_if_duplicate options
  513. if (!array_key_exists('select_if_duplicate', $table_data)) {
  514. $table_data['select_if_duplicate'] = 0;
  515. }
  516. if (!array_key_exists('update_if_duplicate', $table_data)) {
  517. $table_data['update_if_duplicate'] = 0;
  518. }
  519. // if "select if duplicate" is enabled then check to ensure unique constraint is not violated.
  520. // If it is violated then simply return, the record already exists in the database.
  521. // We check for "insert_unique" for backwards compatibilty but that mode no longer exists
  522. $data[$priority]['is_duplicate'] = 0;
  523. if (preg_match('/insert_unique/', $table_data['mode']) or
  524. $table_data['select_if_duplicate'] == 1 or
  525. $table_data['update_if_duplicate'] == 1) {
  526. $options = array('is_duplicate' => TRUE);
  527. $duplicate = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values, $options);
  528. // if this is a duplicate then substitute the values in the table_data array so
  529. // that for future records that may depend on this one, they can get the values needed
  530. if ($duplicate and is_array($duplicate) and count($duplicate) == 1) {
  531. $dup_record = $duplicate[0];
  532. // save the duplicate record for later. If this is an update_if_duplicate
  533. // then we'll need this record as the match
  534. $data[$priority]['is_duplicate'] = (array) $dup_record;
  535. // if all we have is one field then we will just use the value returned
  536. // rather than create an array of values. This way it will prevent
  537. // the tripal_core_chado_(select|insert|update) from recursing on
  538. // foreign keys and make the loader go faster.
  539. if (count((array) $dup_record) == 1) {
  540. foreach ($dup_record as $key => $value) {
  541. $data[$priority]['values_array'] = $value;
  542. }
  543. }
  544. // if we have multiple fields returned then we need to set the values
  545. // the new array.
  546. else {
  547. // convert object to array
  548. $new_values = array();
  549. foreach ($dup_record as $key => $value) {
  550. $new_values[$key] = $value;
  551. }
  552. $data[$priority]['values_array'] = $new_values;
  553. }
  554. // return if this is a select_if_duplicate
  555. if ($table_data['select_if_duplicate'] == 1) {
  556. watchdog('T_bulk_loader','Simply returning values for %record since it was already inserted',array('%record'=>$table_data['record_id']),WATCHDOG_NOTICE);
  557. return $no_errors;
  558. }
  559. }
  560. }
  561. else {
  562. # TODO: what to do if there are more than one value returned when
  563. # checking for a duplicate?
  564. }
  565. if (!preg_match('/select/', $table_data['mode'])) {
  566. // Use prepared statement?
  567. if (variable_get('tripal_bulk_loader_prepare', TRUE)) {
  568. $options = array('statement_name' => 'record_' . $addt->nid . '_' . $priority);
  569. if (($addt->line_num > 1 && $addt->group_index == 1) OR $addt->group_index > 1) {
  570. //$options['is_prepared'] = TRUE;
  571. }
  572. }
  573. else {
  574. $options = array();
  575. }
  576. // Skip tripal_core_chado_insert() built-in validation?
  577. if (variable_get('tripal_bulk_loader_skip_validation', FALSE)) {
  578. $options['skip_validation'] = TRUE;
  579. }
  580. if ($table_data['update_if_duplicate'] == 1) {
  581. if (array_key_exists('statement_name', $options)) {
  582. $options['statement_name'] = 'upd_' . $options['statement_name'];
  583. }
  584. // This should have been set on the first round of inserts for this record
  585. $match = $data[$priority]['is_duplicate'];
  586. // However, sometimes there is a pre-existing record before the loader starts
  587. // Thus check that this value is set and if not, then generate a match array
  588. // based on the unique keys for this record.
  589. if (empty($match)) {
  590. $match = array();
  591. // First check to see if we have fields for the primary key
  592. foreach ($table_desc['primary key'] as $k_field) {
  593. if (!empty($values[$k_field])) {
  594. $match[$k_field] = $values[$k_field];
  595. }
  596. }
  597. // Otherwise check the fields that are part of the unique key
  598. if (empty($match)) {
  599. foreach ($table_desc['unique keys'] as $u_keys) {
  600. foreach ($u_keys as $u_field) {
  601. if (!empty($values[$u_field])) {
  602. $match[$u_field] = $values[$u_field];
  603. }
  604. }
  605. }
  606. }
  607. }
  608. if (!empty($match)) {
  609. // Now we need to check if it already exists via a select
  610. $results = tripal_core_chado_select($table, array_keys($table_desc['fields']), $match);
  611. // If not then insert
  612. if (empty($results)) {
  613. $options['statement_name'] = 'ins_'.$options['statement_name'];
  614. $record = tripal_core_chado_insert($table, $values, $options);
  615. }
  616. else {
  617. $options['return_record'] = TRUE;
  618. $record = tripal_core_chado_update($table, $match, $values, $options);
  619. }
  620. }
  621. else {
  622. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' .
  623. $table_data['mode'] . ') Unable to update record since none of the unique key or primary key fields were available ' .
  624. ' where values:' . print_r($values, TRUE);
  625. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  626. $data[$priority]['error'] = TRUE;
  627. $no_errors = FALSE;
  628. }
  629. }
  630. else {
  631. $record = tripal_core_chado_insert($table, $values, $options);
  632. }
  633. // if the insert was not successful
  634. if (!$record) {
  635. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' .
  636. $table_data['mode'] . ') Unable to insert record into ' . $table .
  637. ' where values:' . print_r($values, TRUE);
  638. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  639. $data[$priority]['error'] = TRUE;
  640. $no_errors = FALSE;
  641. }
  642. // if the insert was succesful
  643. else {
  644. // if mode=insert_once then ensure we only insert it once
  645. if (preg_match('/insert_once/', $table_data['mode'])) {
  646. $default_data[$priority]['inserted'] = TRUE;
  647. }
  648. // add to tripal_bulk_loader_inserted
  649. if ($addt->node->keep_track_inserted) {
  650. $insert_record = db_fetch_object(db_query(
  651. "SELECT * FROM {tripal_bulk_loader_inserted} WHERE table_inserted_into='%s' AND nid=%d",
  652. $table,
  653. $addt->nid
  654. ));
  655. if ($insert_record) {
  656. $insert_record->ids_inserted .= ',' . $record[$table_desc['primary key'][0] ];
  657. drupal_write_record('tripal_bulk_loader_inserted', $insert_record, 'tripal_bulk_loader_inserted_id');
  658. //print 'Update: '.print_r($insert_record,TRUE)."\n";
  659. //return $no_errors;
  660. }
  661. else {
  662. $insert_record = array(
  663. 'nid' => $addt->nid,
  664. 'table_inserted_into' => $table,
  665. 'table_primary_key' => $table_desc['primary key'][0],
  666. 'ids_inserted' => $record[ $table_desc['primary key'][0] ],
  667. );
  668. //print 'New: '.print_r($insert_record,TRUE)."\n";
  669. $success = drupal_write_record('tripal_bulk_loader_inserted', $insert_record);
  670. //return $no_errors;
  671. }//end of if insert record
  672. }// end of if keeping track of records inserted
  673. // substitute the values array for the primary key if it exists
  674. // and is a single field
  675. if (array_key_exists('primary key', $table_desc)) {
  676. if (count($table_desc['primary key']) == 1) {
  677. $pkey_field = $table_desc['primary key'][0];
  678. $data[$priority]['values_array'] = $record[$pkey_field];
  679. }
  680. }
  681. else {
  682. //add changes back to values array
  683. $data[$priority]['values_array'] = $record;
  684. $values = $record;
  685. }
  686. } //end of if insert was successful
  687. }
  688. // perform a select
  689. else {
  690. // get the matches for this select
  691. $matches = array();
  692. if (is_array($values) and count($values) > 0) {
  693. $matches = tripal_core_chado_select($table, array_keys($table_desc['fields']), $values);
  694. }
  695. // if the record doesn't exist and it's not optional then generate an error
  696. if (count($matches) == 0) {
  697. // No record on select
  698. if ($table_data['select_optional'] != 1) {
  699. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') No Matching record in ' . $table . ' where values:' . print_r($values, TRUE);
  700. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_ERROR);
  701. $data[$priority]['error'] = TRUE;
  702. $no_errors = FALSE;
  703. }
  704. // there is no match and select optional is turned on, so we want to set
  705. // the values to empty for any records with an FK relationship on this one
  706. else {
  707. $data[$priority]['values_array'] = NULL;
  708. }
  709. }
  710. // if we have more than one record matching and this select isn't optional then fail
  711. if (count($matches) > 1) {
  712. if ($table_data['select_optional'] != 1) {
  713. $msg = "\nLine " . $addt->line_num . ' ' . $table_data['record_id'] . ' (' . $table_data['mode'] . ') Too many matching records in ' . $table . ' where values:' . print_r($values, TRUE);
  714. watchdog('T_bulk_loader', $msg, array(), WATCHDOG_WARNING);
  715. $data[$priority]['error'] = TRUE;
  716. $no_errors = FALSE;
  717. }
  718. // there are too many matches and this is an optional select so set
  719. // the values to empty for any records with an FK relationship on this one
  720. else {
  721. $data[$priority]['values_array'] = NULL;
  722. }
  723. }
  724. // if mode=select_once then ensure we only select it once
  725. if (preg_match('/select_once/', $table_data['mode'])) {
  726. $default_data[$priority]['selected'] = TRUE;
  727. // save the pkey
  728. if (array_key_exists('primary key', $table_desc)) {
  729. $new_values = array();
  730. foreach ($matches[0] as $key => $value) {
  731. $new_values[$key] = $value;
  732. }
  733. $default_data[$priority]['values_default'] = $new_values;
  734. }
  735. }
  736. }
  737. return $no_errors;
  738. }
  739. /**
  740. * This function adds the file data to the values array
  741. *
  742. * @param $values
  743. * The default values array -contains all constants
  744. * @param $line
  745. * An array of values for the current line
  746. * @param $field2column
  747. * An array mapping values fields to line columns
  748. * @return
  749. * Supplemented values array
  750. *
  751. * @ingroup tripal_bulk_loader
  752. */
  753. function tripal_bulk_loader_add_spreadsheetdata_to_values($values, $line, $field2column) {
  754. foreach ($values as $field => $value) {
  755. if (is_array($value)) {
  756. continue;
  757. }
  758. $column = $field2column[$field] - 1;
  759. if ($column < 0) {
  760. continue;
  761. }
  762. if (preg_match('/\S+/', $line[$column])) {
  763. $values[$field] = $line[$column];
  764. }
  765. else {
  766. unset($values[$field]);
  767. }
  768. }
  769. return $values;
  770. }
  771. /**
  772. * Handles foreign keys in the values array.
  773. *
  774. * Specifically, if the value for a field is an array then it is assumed that the array contains
  775. * the name of the record whose values array should be substituted here. Thus the foreign
  776. * record is looked up and the values array is substituted in.
  777. *
  778. * @ingroup tripal_bulk_loader
  779. */
  780. function tripal_bulk_loader_add_foreignkey_to_values($table_array, $values, $data, $record2priority, $nid, $priority, $default_data) {
  781. // iterate through each field in the $values arrray and
  782. // substitute any values for FK / referring fields
  783. foreach ($values as $field => $value) {
  784. // if the field value is an array then it is an FK
  785. if (is_array($value)) {
  786. // get the name and priority of the foreign record
  787. $foreign_record = $value['foreign record']['record'];
  788. $foreign_priority = $record2priority[$foreign_record];
  789. $foreign_table = $value['foreign record']['table'];
  790. $foreign_field = $value['foreign record']['field'];
  791. // get the values of the foreign record and substitute those for the values
  792. $foreign_values = $data[$foreign_priority]['values_array'];
  793. // check to see if we have any default values in the $default_data array
  794. // these were populated from select statements that only need to run once
  795. // so we can reuse the values from those previous selects.
  796. if (array_key_exists($foreign_priority, $default_data) and
  797. array_key_exists('values_default', $default_data[$foreign_priority]) and
  798. array_key_exists($foreign_field, $default_data[$foreign_priority]['values_default'])) {
  799. $values[$field] = $default_data[$foreign_priority]['values_default'][$foreign_field];
  800. continue;
  801. }
  802. // if the field in the Referral records is in a FK relationship with
  803. // this field then we can simply keep the value we have
  804. $tbl_description = tripal_core_get_chado_table_schema($table_array['table']);
  805. if ($tbl_description and
  806. array_key_exists('foreign keys', $tbl_description) and
  807. array_key_exists($foreign_table, $tbl_description['foreign keys']) and
  808. array_key_exists($field, $tbl_description['foreign keys'][$foreign_table]['columns']) and
  809. $foreign_field == $tbl_description['foreign keys'][$foreign_table]['columns'][$field]) {
  810. $values[$field] = $foreign_values;
  811. }
  812. // if the field in the Referral records is not in an FK relationship
  813. // with this field then we we have to get the requested value, we must
  814. // return only a single value
  815. else {
  816. // if the current value of the referral records is a non-array then this
  817. // is the primary key, we can use it to select the value we need.
  818. $fk_description = tripal_core_get_chado_table_schema($foreign_table);
  819. if (!is_array($foreign_values)) {
  820. // if we have a value then use it to get the field we need
  821. if ($foreign_values) {
  822. $fvalues = array($fk_description['primary key'][0] => $foreign_values);
  823. $columns = array($foreign_field);
  824. $options = array('statement_name' => 'pk_' . $foreign_table);
  825. $record = tripal_core_chado_select($foreign_table, $columns, $fvalues, $options);
  826. if ($record) {
  827. $values[$field] = $record[0]->$foreign_field;
  828. }
  829. else {
  830. unset($values[$field]);
  831. }
  832. }
  833. // if we don't have a value then there's nothing we can do so
  834. // set this value to nothing as well
  835. else {
  836. unset($values[$field]);
  837. }
  838. }
  839. // if the current value is an array and our field is not in it, then
  840. // we need to select a value for our field.
  841. else {
  842. $fvalues = $foreign_values;
  843. $columns = array($foreign_field);
  844. $options = array('statement_name' => 'blk_' . $nid . $priority . $foreign_table);
  845. $record = tripal_core_chado_select($foreign_table, $columns, $fvalues, $options);
  846. if ($record) {
  847. $values[$field] = $record[0]->$foreign_field;
  848. }
  849. else {
  850. unset($values[$field]);
  851. }
  852. } // end else from: if (!is_array($foreign_values) ...
  853. } // end else from: if ($tbl_description ...
  854. } // end if(is_array($value)) ...
  855. } // end foreach ($values ...
  856. // return the updated field values
  857. return $values;
  858. }
  859. /**
  860. * Uses a supplied regex to transform spreadsheet values
  861. *
  862. * @param $values
  863. * The select/insert values array for the given table
  864. * @param $table_data
  865. * The data array for the given table
  866. *
  867. * @ingroup tripal_bulk_loader
  868. */
  869. function tripal_bulk_loader_regex_tranform_values($values, $table_data, $line) {
  870. if (!array_key_exists('regex_transform', $table_data) or
  871. empty($table_data['regex_transform']) or
  872. !array_key_exists('regex_transform', $table_data) or
  873. !is_array($table_data['regex_transform'])) {
  874. return $values;
  875. }
  876. //watchdog('T_bulk_loader','Regex Transformation:<pre>'.print_r($table_data['regex_transform'], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  877. foreach ($table_data['regex_transform'] as $field => $regex_array) {
  878. if (!array_key_exists('replace', $regex_array) or
  879. !array_key_exists('pattern', $regex_array) or
  880. !is_array($regex_array['replace'])) {
  881. continue;
  882. }
  883. // Check for <#column:\d+#> notation
  884. // if present replace with that column in the current line
  885. foreach ($regex_array['replace'] as $key => $replace) {
  886. if (preg_match_all('/<#column:(\d+)#>/', $replace, $matches)) {
  887. foreach ($matches[1] as $k => $column_num) {
  888. $replace = preg_replace('/' . $matches[0][$k] .'/', $line[$column_num-1], $replace);
  889. }
  890. $regex_array['replace'][$key] = $replace;
  891. }
  892. }
  893. // do the full replacement
  894. $old_value = $values[$field];
  895. $new_value = preg_replace($regex_array['pattern'], $regex_array['replace'], $old_value);
  896. $values[$field] = $new_value;
  897. if ($values[$field] === '') {
  898. unset($values[$field]);
  899. }
  900. //print 'Now:'.$values[$field]."\n";
  901. }
  902. return $values;
  903. }
  904. /**
  905. * Flattens an array up to two levels
  906. * Used for printing of arrays without taking up much space
  907. *
  908. * @ingroup tripal_bulk_loader
  909. */
  910. function tripal_bulk_loader_flatten_array($values) {
  911. $flattened_values = array();
  912. foreach ($values as $k => $v) {
  913. if (is_array($v)) {
  914. $vstr = array();
  915. foreach ($v as $vk => $vv) {
  916. if (drupal_strlen($vv) > 20) {
  917. $vstr[] = $vk . '=>' . drupal_substr($vv, 0, 20) . '...';
  918. }
  919. else {
  920. $vstr[] = $vk . '=>' . $vv;
  921. }
  922. }
  923. $v = '{' . implode(',', $vstr) . '}';
  924. }
  925. elseif (drupal_strlen($v) > 20) {
  926. $v = drupal_substr($v, 0, 20) . '...';
  927. }
  928. $flattened_values[] = $k . '=>' . $v;
  929. }
  930. return implode(', ', $flattened_values);
  931. }
  932. /**
  933. * Used to display loader progress to the user
  934. *
  935. * @ingroup tripal_bulk_loader
  936. */
  937. function tripal_bulk_loader_progress_bar($current=0, $total=100, $size=50) {
  938. $new_bar = FALSE;
  939. $mem = memory_get_usage();
  940. // First iteration
  941. if ($current == 0) {
  942. $new_bar = TRUE;
  943. fputs(STDOUT, "Progress:\n");
  944. }
  945. // Percentage round off for a more clean, consistent look
  946. $percent = sprintf("%.02f", round(($current/$total) * 100, 2));
  947. // percent indicator must be four characters, if shorter, add some spaces
  948. for ($i = strlen($percent); $i <= 4; $i++) {
  949. $percent = ' ' . $percent;
  950. }
  951. $total_size = $size + $i + 3 + 2;
  952. $place = 0;
  953. // if it's not first go, remove the previous bar
  954. if (!$new_bar) {
  955. for ($place = $total_size; $place > 0; $place--) {
  956. // echo a backspace (hex:08) to remove the previous character
  957. //echo "\x08";
  958. }
  959. }
  960. // output the progess bar as it should be
  961. // Start with a border
  962. echo '[';
  963. for ($place = 0; $place <= $size; $place++) {
  964. // output "full" spaces if this portion is completed
  965. if ($place <= ($current / $total * $size)) {
  966. echo '|';
  967. }
  968. else {
  969. // Otherwise empty space
  970. echo '-';
  971. }
  972. }
  973. // End with a border
  974. echo ']';
  975. // end a bar with a percent indicator
  976. echo " $percent%. ($current of $total) Memory: $mem\r";
  977. // if it's the end, add a new line
  978. if ($current == $total) {
  979. echo "\n";
  980. }
  981. }
  982. /**
  983. * Keep track of progress in file rather then database
  984. *
  985. * This provides an alternative method to keep track of progress that doesn't require the
  986. * database. It was needed because you can't switch databases within a transaction...
  987. * Waiting until the end of a constant set is much too long to wait for any indication
  988. * that things are working.
  989. *
  990. * Each line represents a line processed in the loading file. Each period (.) represents
  991. * a successfully inserted record.
  992. *
  993. * @param $job_id
  994. * The ID of the current tripal job
  995. * @param $record_added
  996. * A boolean indicated whether a record was added successfully
  997. * @param $line_complete
  998. * A boolean indicating whether the current line is finished
  999. * @param $close
  1000. * A boolean indicating that the file should be closed
  1001. *
  1002. * @ingroup tripal_bulk_loader
  1003. */
  1004. function tripal_bulk_loader_progress_file_track_job($job_id, $record_added, $line_complete = FALSE, $close = FALSE) {
  1005. // retrieve the file handle
  1006. $file_handle = variable_get('tripal_bulk_loader_progress_file_handle', NULL);
  1007. // open file for reading if not already
  1008. if (!$file_handle) {
  1009. $file_handle = fopen('/tmp/tripal_bulk_loader_progress-'. $job_id . '.out', 'w');
  1010. variable_set('tripal_bulk_loader_progress_file_handle', $file_handle);
  1011. }
  1012. if ($record_added) {
  1013. fwrite($file_handle, '.');
  1014. }
  1015. if ($line_complete) {
  1016. fwrite($file_handle, "\n");
  1017. }
  1018. // close the file if finished
  1019. if ($close) {
  1020. fclose($file_handle);
  1021. variable_set('tripal_bulk_loader_progress_file_handle', NULL);
  1022. }
  1023. }