tripal_bulk_loader.loader.inc 40 KB

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