tripal_chado.mviews.api.inc 13 KB

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