tripal_chado.mviews.api.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. <?php
  2. /**
  3. * @file
  4. * Provides an application programming interface (API) to manage materialized
  5. * views in Chado.
  6. */
  7. /**
  8. * @defgroup tripal_mviews_api Chado Materalized Views
  9. * @ingroup tripal_chado_api
  10. * @{
  11. * Provides an application programming interface (API) to manage materialized
  12. * views in Chado The Perl-based chado comes with an interface for managing
  13. * materialzed views. This API provides an alternative Drupal-based method.
  14. * @}
  15. */
  16. /**
  17. * Add a materialized view to the chado database to help speed data access. This
  18. * function supports the older style where postgres column specifications
  19. * are provided using the $mv_table, $mv_specs and $indexed variables. It also
  20. * supports the newer preferred method where the materialized view is described
  21. * using the Drupal Schema API array.
  22. *
  23. * @param $name
  24. * The name of the materialized view.
  25. * @param $modulename
  26. * The name of the module submitting the materialized view
  27. * (e.g. 'tripal_library').
  28. * @param $mv_schema
  29. * If using the newer Schema API array to define the materialized view then
  30. * this variable should contain the array or a string representation of the
  31. * array.
  32. * @param $query
  33. * The SQL query that loads the materialized view with data.
  34. * @param $comment
  35. * A string containing a description of the materialized view.
  36. * @param $redirect
  37. * Optional (default: TRUE). By default this function redirects back to
  38. * admin pages. However, when called by Drush we don't want to redirect. This
  39. * parameter allows this to be used as a true API function.
  40. *
  41. * @return
  42. * TRUE if the materialized view was successfully addd, FALSE otherwise.
  43. * @ingroup tripal_mviews_api
  44. */
  45. function chado_add_mview($name, $modulename, $mv_schema, $query, $comment = NULL, $redirect = TRUE) {
  46. if (!array_key_exists('table', $mv_schema)) {
  47. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  48. 'Must have a table name when creating an mview.', array());
  49. return FALSE;
  50. }
  51. $mv_table = $mv_schema['table'];
  52. // See if the mv_table name already exsists.
  53. $mview_id = db_select('tripal_mviews', 'tm')
  54. ->fields('tm', array('mview_id'))
  55. ->condition('name', $name)
  56. ->execute()
  57. ->fetchField();
  58. // Check that the materialized view actually exists and if not,
  59. // remove the entry from tripal_mviews.
  60. if ($mview_id AND !chado_table_exists($name)) {
  61. db_delete('tripal_mviews')
  62. ->condition('mview_id', $mview_id)
  63. ->execute();
  64. $mview_id = FALSE;
  65. }
  66. if(!$mview_id) {
  67. $transaction = db_transaction();
  68. try {
  69. // Create a new record.
  70. $record = new stdClass();
  71. $record->name = $name;
  72. $record->modulename = $modulename;
  73. $record->mv_table = $mv_table;
  74. $record->query = $query;
  75. $record->comment = $comment;
  76. // Convert the schema into a string format.
  77. $str_schema = var_export($mv_schema, TRUE);
  78. $str_schema = preg_replace('/=>\s+\n\s+array/', '=> array', $str_schema);
  79. $record->mv_schema = $str_schema;
  80. // Add the record to the tripal_mviews table and if successful
  81. // create the new materialized view in the chado schema.
  82. if (drupal_write_record('tripal_mviews', $record)) {
  83. // Drop the table from chado if it exists.
  84. if (chado_table_exists($mv_table)) {
  85. $sql = 'DROP TABLE {' . $mv_table . '}';
  86. chado_query($sql);
  87. }
  88. // Create the table.
  89. chado_create_custom_table($mv_table, $mv_schema, 0, $record->mview_id, $redirect);
  90. }
  91. }
  92. catch (Exception $e) {
  93. $transaction->rollback();
  94. watchdog_exception('tripal_chado', $e);
  95. $error = _drupal_decode_exception($e);
  96. drupal_set_message(t("Could not create the materialized view %table_name: %message.",
  97. array('%table_name' => $name, '%message' => $error['!message'])), 'error');
  98. return FALSE;
  99. }
  100. drupal_set_message(t("Materialized view '%name' created", array('%name' => $name)));
  101. return TRUE;
  102. }
  103. else {
  104. drupal_set_message(t("Materialized view, $name, already exists. Skipping creation.", array('%name' => $name)));
  105. return FALSE;
  106. }
  107. }
  108. /**
  109. * Edits a materialized view to the chado database to help speed data access.
  110. * This function supports the older style where postgres column specifications
  111. * are provided using the $mv_table, $mv_specs and $indexed variables. It also
  112. * supports the newer preferred method where the materialized view is described
  113. * using the Drupal Schema API array.
  114. *
  115. * @param $mview_id
  116. * The mview_id of the materialized view to edit.
  117. * @param $name
  118. * The name of the materialized view.
  119. * @param $modulename
  120. * The name of the module submitting the materialized view
  121. * (e.g. 'tripal_library').
  122. * @param $mv_table
  123. * The name of the table to add to chado. This is the table that can be
  124. * queried.
  125. * @param $mv_specs
  126. * The table definition.
  127. * @param $indexed
  128. * The columns that are to be indexed.
  129. * @param $query
  130. * The SQL query that loads the materialized view with data.
  131. * @param $special_index
  132. * currently not used.
  133. * @param $comment
  134. * A string containing a description of the materialized view.
  135. * @param $mv_schema
  136. * If using the newer Schema API array to define the materialized view then
  137. * this variable should contain the array.
  138. *
  139. * @ingroup tripal_mviews_api
  140. */
  141. function chado_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
  142. $indexed, $query, $special_index, $comment = NULL, $mv_schema = NULL) {
  143. $transaction = db_transaction();
  144. try {
  145. // get the table name from the schema array
  146. $schema_arr = array();
  147. if ($mv_schema) {
  148. // get the schema from the mv_specs and use it to add the custom table
  149. eval("\$schema_arr = $mv_schema;");
  150. $mv_table = $schema_arr['table'];
  151. }
  152. $record = new stdClass();
  153. $record->mview_id = $mview_id;
  154. $record->name = $name;
  155. $record->modulename = $modulename;
  156. $record->query = $query;
  157. $record->last_update = 0;
  158. $record->status = '';
  159. $record->comment = $comment;
  160. $record->mv_schema = $mv_schema;
  161. $record->mv_table = $mv_table;
  162. // update the record to the tripal_mviews table
  163. drupal_write_record('tripal_mviews', $record, 'mview_id');
  164. // get the view before we update and check to see if the table structure has
  165. // changed. If so, then we want to drop and recreate the table. If not, then
  166. // just save the updated SQL.
  167. $create_table = 1;
  168. $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id";
  169. $results = db_query($sql, array(':mview_id' => $mview_id));
  170. $mview = $results->fetchObject();
  171. if ($mview->mv_schema == $mv_schema and $mview->mv_table == $mv_table) {
  172. chado_create_custom_table($mv_table, $schema_arr, 0, $record->mview_id);
  173. drupal_set_message(t("Materialized view '%name' created", array('%name' => $name)));
  174. }
  175. else {
  176. $message = "View '%name' updated. All records remain. ";
  177. if ($query != $mview->query) {
  178. $message .= "Please repopulate the view to use the updated query.";
  179. }
  180. drupal_set_message(t($message, array('%name' => $name)));
  181. }
  182. // construct the indexes SQL if needed
  183. $index = '';
  184. if ($indexed) {
  185. // add to the array of values
  186. $vals = preg_split("/[\n,]+/", $indexed);
  187. $index = '';
  188. foreach ($vals as $field) {
  189. $field = trim($field);
  190. $index .= "CREATE INDEX idx_${mv_table}_${field} ON $mv_table ($field);";
  191. }
  192. }
  193. }
  194. catch (Exception $e) {
  195. $transaction->rollback();
  196. watchdog_exception('tripal_chado', $e);
  197. $error = _drupal_decode_exception($e);
  198. drupal_set_message(t("Could not update materialized view '%table_name': %message.",
  199. array('%table_name' => $mv_table, '%message' => $error['!message'])), 'error');
  200. return FALSE;
  201. }
  202. }
  203. /**
  204. * Retrieve the materialized view_id given the name.
  205. *
  206. * @param $view_name
  207. * The name of the materialized view.
  208. *
  209. * @return
  210. * The unique identifier for the given view.
  211. *
  212. * @ingroup tripal_mviews_api
  213. */
  214. function chado_get_mview_id($view_name) {
  215. if (db_table_exists('tripal_mviews')) {
  216. $sql = "SELECT * FROM {tripal_mviews} WHERE name = :name";
  217. $results = db_query($sql, array(':name' => $view_name));
  218. $mview = $results->fetchObject();
  219. if ($mview) {
  220. return $mview->mview_id;
  221. }
  222. }
  223. return FALSE;
  224. }
  225. /**
  226. * Retrieves the list of materialized views in this site.
  227. *
  228. * @returns
  229. * An associative array where the key and value pairs are the table names.
  230. *
  231. * @ingroup tripal_mviews_api
  232. */
  233. function chado_get_mview_table_names() {
  234. $sql = "SELECT name FROM {tripal_mviews}";
  235. $resource = db_query($sql);
  236. $tables = array();
  237. foreach ($resource as $r) {
  238. $tables[$r->name] = $r->name;
  239. }
  240. asort($tables);
  241. return $tables;
  242. }
  243. /**
  244. * Populates the specified Materialized View.
  245. *
  246. * @param $mview_id
  247. * The unique ID of the materialized view for the action to be performed on.
  248. *
  249. * @ingroup tripal_mviews_api
  250. */
  251. function chado_refresh_mview($mview_id) {
  252. global $user;
  253. if (!$mview_id) {
  254. return '';
  255. }
  256. // Get this mview details.
  257. $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id";
  258. $results = db_query($sql, array(':mview_id' => $mview_id));
  259. $mview = $results->fetchObject();
  260. // Add a job to populate the mview.
  261. $args = array("$mview_id");
  262. tripal_add_job("Populate materialized view '$mview->name'", 'tripal_chado',
  263. 'chado_populate_mview', $args, $user->uid);
  264. }
  265. /**
  266. * Retrieves the list of materialized view IDs and their names.
  267. *
  268. * @return
  269. * An array of objects with the following properties: mview_id, name.
  270. *
  271. * @ingroup tripal_mviews_api
  272. *
  273. */
  274. function chado_get_mviews() {
  275. $results = db_select('tripal_mviews', 'tm')
  276. ->fields('tm', array('mview_id', 'name'))
  277. ->execute();
  278. $list = array();
  279. while ($mview = $results->fetchObject()) {
  280. $list[] = $mview;
  281. }
  282. return $list;
  283. }
  284. /**
  285. * Does the specified action for the specified Materialized View.
  286. *
  287. * @param $op
  288. * The action to be taken. One of update or delete.
  289. * @param $mview_id
  290. * The unique ID of the materialized view for the action to be performed on.
  291. *
  292. * @ingroup tripal_mviews_api
  293. */
  294. function chado_delete_mview($mview_id) {
  295. global $user;
  296. if (!$mview_id) {
  297. return '';
  298. }
  299. // Get this mview details.
  300. $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id";
  301. $results = db_query($sql, array(':mview_id' => $mview_id));
  302. $mview = $results->fetchObject();
  303. // If op is to delete then do so.
  304. // Remove the mview from the tripal_mviews table.
  305. $sql = "DELETE FROM {tripal_mviews} WHERE mview_id = $mview_id";
  306. db_query($sql);
  307. // Does the table already exist?
  308. $mview_exists = chado_table_exists($mview->mv_table);
  309. // Drop the table from chado if it exists.
  310. if ($mview_exists) {
  311. $sql = "DROP TABLE {" . $mview->mv_table . "}";
  312. $success = chado_query($sql);
  313. if ($success) {
  314. drupal_set_message(t("Materialized view, %name, deleted.", array('%name' => $mview->name)));
  315. }
  316. else {
  317. drupal_set_message(t("Problem deleting materialized view, %name.", array('%name' => $mview->name)), 'error');
  318. }
  319. }
  320. }
  321. /**
  322. * Update a Materialized View.
  323. *
  324. * @param $mview_id
  325. * The unique identifier for the materialized view to be updated.
  326. *
  327. * @return
  328. * True if successful, FALSE otherwise.
  329. *
  330. * @ingroup tripal_mviews_api
  331. */
  332. function chado_populate_mview($mview_id) {
  333. $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id ";
  334. $results = db_query($sql, array(':mview_id' => $mview_id));
  335. $mview = $results->fetchObject();
  336. if ($mview) {
  337. // Execute the query inside a transaction so that it doesn't destroy
  338. // existing data that may leave parts of the site unfunctional.
  339. $transaction = db_transaction();
  340. $previous_db = chado_set_active('chado'); // use chado database
  341. try {
  342. $success = chado_query("DELETE FROM {" . $mview->mv_table . "}");
  343. $success = chado_query("INSERT INTO {" . $mview->mv_table . "} ($mview->query)");
  344. // If success get the number of results and update the table record.
  345. if ($success) {
  346. $sql = "SELECT count(*) as cnt FROM {" . $mview->mv_table . "}";
  347. $results = chado_query($sql);
  348. $count = $results->fetchObject();
  349. $record = new stdClass();
  350. $record->mview_id = $mview_id;
  351. $record->last_update = time();
  352. $record->status = "Populated with " . number_format($count->cnt) . " rows";
  353. drupal_write_record('tripal_mviews', $record, 'mview_id');
  354. }
  355. // If not success then throw an error.
  356. else {
  357. throw new Exception("ERROR populating the materialized view ". $mview->mv_table . ". See Drupal's recent log entries for details.");
  358. }
  359. chado_set_active($previous_db);
  360. }
  361. catch (Exception $e) {
  362. $transaction->rollback();
  363. chado_set_active($previous_db);
  364. // Print and save the error message.
  365. $record = new stdClass();
  366. $record->mview_id = $mview_id;
  367. $record->status = "ERROR populating $mview->mv_table. See Drupal's recent log entries for details.\n";
  368. drupal_write_record('tripal_mviews', $record, 'mview_id');
  369. watchdog_exception('tripal_mviews', $e);
  370. return FALSE;
  371. }
  372. print "Done.\n";
  373. return TRUE;
  374. }
  375. }