tripal_bulk_loader.loader.inc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. foreach ($record_array['fields'] as $field_index => $field_array) {
  141. $default_data[$priority]['table'] = $record_array['table'];
  142. $default_data[$priority]['mode'] = ($record_array['mode']) ? $record_array['mode'] : 'insert';
  143. $default_data[$priority]['select_if_duplicate'] = ($record_array['select_if_duplicate']) ? $record_array['select_if_duplicate'] : 0;
  144. $default_data[$priority]['update_if_duplicate'] = ($record_array['update_if_duplicate']) ? $record_array['update_if_duplicate'] : 0;
  145. $default_data[$priority]['disabled'] = ($record_array['disable']) ? $record_array['disable'] : 0;
  146. $default_data[$priority]['optional'] = ($record_array['optional']) ? $record_array['optional'] : 0;
  147. $default_data[$priority]['select_optional'] = ($record_array['select_optional']) ? $record_array['select_optional'] : 0;
  148. $default_data[$priority]['record_id'] = $record_array['record_id'];
  149. $default_data[$priority]['required'][$field_array['field']] = $field_array['required'];
  150. $one = $default_data[$priority];
  151. if (isset($field_array['regex'])) {
  152. $default_data[$priority]['regex_transform'][$field_array['field']] = $field_array['regex'];
  153. }
  154. $two = $default_data[$priority];
  155. if (preg_match('/table field/', $field_array['type'])) {
  156. $default_data[$priority]['values_array'][$field_array['field']] = '';
  157. $default_data[$priority]['need_further_processing'] = TRUE;
  158. $field2column[$priority][$field_array['field']] = $field_array['spreadsheet column'];
  159. }
  160. elseif (preg_match('/constant/', $field_array['type'])) {
  161. $default_data[$priority]['values_array'][$field_array['field']] = $field_array['constant value'];
  162. }
  163. elseif (preg_match('/foreign key/', $field_array['type'])) {
  164. $default_data[$priority]['values_array'][$field_array['field']] = array();
  165. $default_data[$priority]['need_further_processing'] = TRUE;
  166. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['record'] = $field_array['foreign key'];
  167. // Add in the FK / Referral table
  168. $fk_priority = $record2priority[$field_array['foreign key']];
  169. $fk_table = $template_array[$fk_priority]['table'];
  170. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['table'] = $fk_table;
  171. // Add in the FK / Referral field
  172. // for backwards compatibility we need to get the FK relationship to find
  173. // out what field we're joining on. For templates created using a
  174. // previous version it was assumed that the FK field was always the field to join
  175. if (!array_key_exists('foreign field', $field_array)) {
  176. $tbl_description = tripal_core_get_chado_table_schema($record_array['table']);
  177. foreach ($tbl_description['foreign keys'] as $key_table => $key_array) {
  178. if ($key_table == $fk_table) {
  179. foreach ($key_array['columns'] as $left_field => $right_field) {
  180. if ($left_field == $field_array['field']) {
  181. $field_array['foreign field'] = $right_field;
  182. }
  183. }
  184. }
  185. }
  186. }
  187. $default_data[$priority]['values_array'][$field_array['field']]['foreign record']['field'] = $field_array['foreign field'];
  188. }
  189. else {
  190. print 'WARNING: Unsupported type: ' . $field_array['type'] . ' for ' . $table . '.' . $field_array['field'] . "!\n";
  191. }
  192. $three = $default_data[$priority];
  193. //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);
  194. } // end of foreach field
  195. //watchdog('T_bulk_loader','2)'.$record_array['record_id'].':<pre>'.print_r($default_data[$priority], TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  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. //print "Default Data:".print_r($default_data,TRUE)."\n";
  238. //watchdog('T_bulk_loader','Default Data:<pre>'.print_r($default_data, TRUE).'</pre>', array(), WATCHDOG_NOTICE);
  239. //print "\nDefault Values Array: ".print_r($default_data, TRUE)."\n";
  240. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  241. // Parse File adding records as we go ========================================================
  242. print "\tPreparing to load the current constant set...\n";
  243. // Open File
  244. print "\t\tOpen File...\n";
  245. $file_handle = fopen($node->file, 'r');
  246. // Set defaults
  247. if (preg_match('/(t|true|1)/', $node->file_has_header)) {
  248. // SPF: Some of our templates had lines longer than 4096 so had to replace this
  249. //fgets($file_handle, 4096);
  250. fgets($file_handle);
  251. }
  252. $num_records = 0;
  253. $num_lines = 0;
  254. $num_errors = 0;
  255. $interval = intval($total_lines * 0.0001);
  256. if ($interval == 0) {
  257. $interval = 1;
  258. }
  259. // Start Transaction
  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 (!feof($file_handle)) {
  295. // Clear variables
  296. // Was added to fix memory leak
  297. unset($line); unset($raw_line);
  298. unset($data); unset($data_keys);
  299. unset($priority); unset($sql);
  300. unset($result);
  301. // SPF: had to remove the length on fgets as some of our templates had lines that were larger
  302. // $raw_line = fgets($file_handle, 4096);
  303. $raw_line = fgets($file_handle);
  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, $columns, $values, $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, $columns, $values, $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. }