tripal_bulk_loader.loader.inc 38 KB

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