tripal_bulk_loader.loader.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. /**
  3. * Add Loader Job Form
  4. *
  5. * This form is meant to be included on the node page to allow users to submit/re-submit
  6. * loading jobs
  7. */
  8. function tripal_bulk_loader_add_loader_job_form ($form_state, $node) {
  9. $form = array();
  10. $form['nid'] = array(
  11. '#type' => 'hidden',
  12. '#value' => $node->nid,
  13. );
  14. $form['file'] = array(
  15. '#type' => 'hidden',
  16. '#value' => $node->file
  17. );
  18. $form['submit'] = array(
  19. '#type' => 'submit',
  20. '#value' => 'Submit Job'
  21. );
  22. return $form;
  23. }
  24. /**
  25. * Add Loader Job Form (Submit)
  26. */
  27. function tripal_bulk_loader_add_loader_job_form_submit ($form, $form_state) {
  28. global $user;
  29. if (preg_match('/Submit Job/', $form_state['values']['op'])) {
  30. //Submit Tripal Job
  31. $job_args[1] = $form_state['values']['nid'];
  32. if (is_readable($form_state['values']['file'])) {
  33. $fname = basename($form_state['values']['file']);
  34. tripal_add_job("Bulk Loading Job: $fname",'tripal_bulk_loader', 'tripal_bulk_loader_load_data', $job_args, $user->uid);
  35. } else {
  36. drupal_set_message("Can not open ".$form_state['values']['file'].". Job not scheduled.");
  37. }
  38. }
  39. }
  40. /**
  41. * Tripal Bulk Loader
  42. *
  43. * This is the function that's run by tripal_launch_jobs to bulk load chado data.
  44. * @param $nid
  45. * The Node ID of the bulk loading job node to be loaded. All other needed data is expected to be
  46. * in the node (ie: template ID and file)
  47. *
  48. * Note: Instead of returning a value this function updates the tripal_bulk_loader.status and
  49. * Enters errors into tripal_bulk_loader_errors if they are encountered.
  50. */
  51. function tripal_bulk_loader_load_data($nid) {
  52. $node = node_load($nid);
  53. print "Template: ".$node->template->name." (".$node->template_id.")\n";
  54. print "File: ".$node->file."\n";
  55. // Prep Work ==================================================================================
  56. // get base table and it's table_description array
  57. $base_table = $node->template->template_array['module'];
  58. $base_table_desc = module_invoke_all('chado_'.$base_table.'_schema');
  59. $related_tables = module_invoke_all('tripal_bulk_loader_'.$base_table.'_related_tables');
  60. //print "Base Table: ".print_r($base_table,TRUE)."\nTable DEscription: ".print_r($base_table_desc, TRUE)."\nTemplate array: ".print_r($node->template->template_array,TRUE)."\n";
  61. // get a default values array to be passed into tripal_core_chado_insert
  62. // and get a mapping between table.field and spreadsheet column
  63. // also determine relationship between each table and base table
  64. $default_values_array = array();
  65. $field2column = array();
  66. $relationships2base = array();
  67. $all_tables = array();
  68. foreach ($node->template->template_array as $table => $table_groups) {
  69. foreach ($table_groups as $group => $table_array) {
  70. if (is_array($table_array)) {
  71. $all_tables[$table] = $table;
  72. foreach ($table_array['field'] as $field_array) {
  73. if (preg_match('/table field/', $field_array['type'])) {
  74. $default_values_array[$table][$group][$field_array['field']] = '';
  75. $field2column[$table][$group][$field_array['field']] = $field_array['spreadsheet column'];
  76. } elseif (preg_match('/constant/', $field_array['type'])) {
  77. $default_values_array[$table][$group][$field_array['field']] = $field_array['constant value'];
  78. } else {
  79. print 'WARNING: Unsupported type: '. $field_array['type'] . ' for ' . $table . '.' . $field_array['field']."!\n";
  80. }
  81. }
  82. // Determine what relation is between this table and the base table-----------------------
  83. // This is used later to link the various records
  84. // Is there a foreign key to this table in the base table?
  85. if ($related_tables['Foreign Key Relations'][$table]) {
  86. $relationships2base['foreign key'][$table] = $base_table_desc['foreign keys'][$table];
  87. }
  88. // Is there a foreign key in this table to the base table?
  89. // ie: featureloc.feature_id (current) for feature (base)
  90. if ($related_tables['Direct Relations'][$table]) {
  91. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  92. $relationships2base['direct'][$table] = $table_desc['foreign keys'][$base_table];
  93. }
  94. // Is there a linking table which links this table with the base table
  95. if ($related_tables['Indirect Relations'][$table]) {
  96. $table_desc = module_invoke_all('chado_'.$table.'_schema');
  97. $relationships2base['indirect'][$table] = $table_desc['foreign keys'];
  98. }
  99. }
  100. }
  101. } //end of preprocessing
  102. //print "\nDefault Values Array: ".print_r($default_values_array, TRUE)."\n";
  103. //print "\nField to Column Mapping: ".print_r($field2column, TRUE)."\n";
  104. //print "\nRelationships to Base Table: ".print_r($relationships2base, TRUE)."\n";
  105. // Parse File adding records as we go ========================================================
  106. $file_handle = fopen($node->file, 'r');
  107. if (preg_match('/(t|true|1)/', $node->file_has_header)) { fgets($file_handle, 4096); }
  108. $num_records = 0;
  109. $num_lines = 0;
  110. $num_errors = 0;
  111. while (!feof($file_handle)) {
  112. $line = array();
  113. $raw_line = fgets($file_handle, 4096);
  114. $line = preg_split("/\t/", $raw_line);
  115. $num_lines++;
  116. // Contains constants set above
  117. $tables = $all_tables;
  118. $values = $default_values_array;
  119. // Insert base record-----------------------------------------------------------------------
  120. foreach ($relationships2base['foreign key'] as $table => $desc) {
  121. // check there is only 1 group & if more than one use first and warn
  122. if (sizeof($values[$table]) > 1) {
  123. print "WARNING: ".$table." has more than one group. There can only be one group for a "
  124. ."table related to the base by a foreign key. Only the first will be used.\n";
  125. }
  126. // Ensure foreign key is present
  127. $group = key($values[$table]);
  128. $sub_values = $values[$table][$group];
  129. $sub_values = tripal_bulk_loader_supplement_values_array ($sub_values, $line, $field2column[$table][$group]);
  130. $values[$table][$group] = $sub_values;
  131. $success = tripal_bulk_loader_ensure_record ($table, $sub_values);
  132. if ($success) {
  133. $num_records++;
  134. } else {
  135. $num_errors++;
  136. }
  137. //Add to base values array
  138. foreach ($desc['columns'] as $foreign_key => $primary_key) {
  139. // check there is only 1 group & if more than one use first and warn
  140. if (sizeof($values[$base_table]) > 1) {
  141. print "WARNING: ".$table." has more than one group. There can only be one group for a "
  142. ."table related to the base by a foreign key. Only the first will be used.\n";
  143. }
  144. $base_group = key($values[$base_table]);
  145. $values[$base_table][$base_group][$foreign_key] = $values[$table][$group];
  146. }
  147. unset($tables[$table]);
  148. }
  149. // base table
  150. $values[$base_table][$base_group] = tripal_bulk_loader_supplement_values_array ($values[$base_table][$base_group], $line, $field2column[$base_table][$base_group]);
  151. $success = tripal_bulk_loader_ensure_record ($base_table, $values[$base_table][$base_group]);
  152. //print 'Base Table values array: '.print_r($values[$base_table], TRUE)."\n";
  153. if (!$success) {
  154. print "ERROR: Unable to insert base record where base table: ".$base_table.
  155. " and values array: ".tripal_bulk_loader_flatten_array($values[$base_table][$base_group])."\n";
  156. $num_errors++;
  157. } else {
  158. $num_records++;
  159. }
  160. unset($tables[$base_table]);
  161. // Insert all tables with direct relationship to base ----------------------------------------
  162. foreach ($relationships2base['direct'] as $table => $desc) {
  163. foreach ($values[$table] as $group => $sub_values) {
  164. //Add base to values array
  165. foreach ($desc['columns'] as $foreign_key => $primary_key) {
  166. $values[$table][$group][$foreign_key] = $values[$base_table][$base_group];
  167. }
  168. // Supplement and Add record
  169. $values[$table][$group] = tripal_bulk_loader_supplement_values_array ($values[$table][$group], $line, $field2column[$table][$group]);
  170. $success = tripal_bulk_loader_ensure_record ($table, $values[$table][$group]);
  171. if ($success) {
  172. $num_records++;
  173. } else {
  174. $num_errors++;
  175. }
  176. unset($tables[$table]);
  177. }
  178. }
  179. // Add in all other tables -----------------------------------------------------------------
  180. foreach ($tables as $table) {
  181. // Don't insert if its an indirect relationship linking table
  182. if (!$relationships2base['indirect'][$table]) {
  183. foreach ($values[$table] as $group => $sub_values) {
  184. // Supplement and Add record
  185. $values[$table][$group] = tripal_bulk_loader_supplement_values_array ($values[$table][$group], $line, $field2column[$table][$group]);
  186. $success = tripal_bulk_loader_ensure_record ($table, $values[$table][$group]);
  187. if ($success) {
  188. $num_records++;
  189. } else {
  190. $num_errors++;
  191. }
  192. }
  193. }
  194. }
  195. // Add in indirect relationships -----------------------------------------------------------
  196. foreach ($relationships2base['indirect'] as $table => $desc) {
  197. foreach ($values[$table] as $group => $sub_values) {
  198. // Add foreign keys to values array
  199. foreach ($desc as $subtable => $subdesc) {
  200. foreach ($subdesc['columns'] as $foreign_key => $primary_key) {
  201. $values[$table][$group][$foreign_key] = $values[$subtable][$group];
  202. }
  203. }
  204. // Supplement and Add record
  205. $values[$group][$table] = tripal_bulk_loader_supplement_values_array ($values[$table][$group], $line, $field2column[$table][$group]);
  206. $success = tripal_bulk_loader_ensure_record ($table, $values[$table][$group]);
  207. if ($success) {
  208. $num_records++;
  209. } else {
  210. $num_errors++;
  211. }
  212. }
  213. }
  214. } //end of file
  215. print "\nNumber of Records Inserted:".$num_records."\n";
  216. print "Number of Lines in File:".$num_lines."\n";
  217. print "Number of Errors: ".$num_errors."\n\n";
  218. if (!$num_errors) {
  219. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'successfully loaded', $nid);
  220. } else {
  221. db_query("UPDATE {tripal_bulk_loader} SET job_status='%s' WHERE nid=%d", 'load attempted', $nid);
  222. }
  223. }
  224. /**
  225. * This function adds the file data to the values array
  226. *
  227. * @param $values
  228. * The default values array -contains all constants
  229. * @param $line
  230. * An array of values for the current line
  231. * @param $field2column
  232. * An array mapping values fields to line columns
  233. * @return
  234. * Supplemented values array
  235. */
  236. function tripal_bulk_loader_supplement_values_array ($values, $line, $field2column) {
  237. foreach ($values as $field => $value) {
  238. $column = $field2column[$field] - 1;
  239. if ($line[$column] OR (!$values[$field])) {
  240. $values[$field] = $line[$column];
  241. }
  242. }
  243. return $values;
  244. }
  245. /**
  246. * This function first ensures the record doesn't already exist and then inserts it
  247. *
  248. * @param $table
  249. * The table the record should be present in
  250. * @param $values
  251. * The values array used for selecting and/or inserting the record
  252. * @return
  253. * TRUE or FALSE based on presence or absence of record
  254. */
  255. function tripal_bulk_loader_ensure_record ($table, $values) {
  256. // get flattened values array for printing errors
  257. $flattened_values = tripal_bulk_loader_flatten_array($values);
  258. // check if record exists
  259. $has_record = tripal_core_chado_select($table, array_keys($values), $values, array('has_record' => TRUE));
  260. if ($has_record) {
  261. print "\tWARNING: Record already exists in $table where ".implode(',',$flattened_values).".\n";
  262. return true;
  263. } else {
  264. // if record doesn't exist then insert it
  265. $success = tripal_core_chado_insert($table, $values);
  266. if (!$success) {
  267. print "ERROR: Unable to insert the following record into $table: ".implode(',',$flattened_values)."\n";
  268. return false;
  269. } else {
  270. return true;
  271. }
  272. }
  273. }
  274. /**
  275. * Flattens an array up to two levels
  276. * Used for printing of arrays without taking up much space
  277. */
  278. function tripal_bulk_loader_flatten_array ($values) {
  279. $flattened_values = array();
  280. foreach ($values as $k => $v) {
  281. if (is_array($v)) {
  282. $vstr = array();
  283. foreach ($v as $vk => $vv) {
  284. if (strlen($vv) > 20) {
  285. $vstr[] = $vk .'=>'. substr($vv, 0, 20) . '...';
  286. } else {
  287. $vstr[] = $vk .'=>'. $vv;
  288. }
  289. }
  290. $v = '{'. implode(',',$vstr) .'}';
  291. } elseif (strlen($v) > 20) {
  292. $v = substr($v, 0, 20) . '...';
  293. }
  294. $flattened_values[] = $k .'=>'. $v;
  295. }
  296. return $flattened_values;
  297. }