tripal_chado.mviews.api.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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.
  18. *
  19. * @param $name
  20. * The name of the materialized view.
  21. * @param $modulename
  22. * The name of the module submitting the materialized view
  23. * (e.g. 'tripal_library').
  24. * @param $mv_schema
  25. * If using the newer Schema API array to define the materialized view then
  26. * this variable should contain the array or a string representation of the
  27. * array.
  28. * @param $query
  29. * The SQL query that loads the materialized view with data.
  30. * @param $comment
  31. * A string containing a description of the materialized view.
  32. * @param $redirect
  33. * Optional (default: TRUE). By default this function redirects back to
  34. * admin pages. However, when called by Drush we don't want to redirect. This
  35. * parameter allows this to be used as a true API function.
  36. *
  37. * @return
  38. * TRUE if the materialized view was successfully added, FALSE otherwise.
  39. *
  40. * @ingroup tripal_mviews_api
  41. */
  42. function chado_add_mview($name, $modulename, $mv_schema, $query, $comment = NULL, $redirect = TRUE) {
  43. if (!array_key_exists('table', $mv_schema)) {
  44. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  45. 'Must have a table name when creating an mview.', []);
  46. return FALSE;
  47. }
  48. $mv_table = $mv_schema['table'];
  49. // See if the mv_table name already exsists.
  50. $mview_id = db_select('tripal_mviews', 'tm')
  51. ->fields('tm', ['mview_id'])
  52. ->condition('name', $name)
  53. ->execute()
  54. ->fetchField();
  55. // Check that the materialized view actually exists and if not,
  56. // remove the entry from tripal_mviews.
  57. if ($mview_id AND !chado_table_exists($name)) {
  58. db_delete('tripal_mviews')
  59. ->condition('mview_id', $mview_id)
  60. ->execute();
  61. $mview_id = FALSE;
  62. }
  63. if (!$mview_id) {
  64. $transaction = db_transaction();
  65. try {
  66. // Create a new record.
  67. $record = new stdClass();
  68. $record->name = $name;
  69. $record->modulename = $modulename;
  70. $record->mv_table = $mv_table;
  71. $record->query = $query;
  72. $record->comment = $comment;
  73. // Convert the schema into a string format.
  74. $str_schema = var_export($mv_schema, TRUE);
  75. $str_schema = preg_replace('/=>\s+\n\s+array/', '=> array', $str_schema);
  76. $record->mv_schema = $str_schema;
  77. // Add the record to the tripal_mviews table and if successful
  78. // create the new materialized view in the chado schema.
  79. if (drupal_write_record('tripal_mviews', $record)) {
  80. // Drop the table from chado if it exists.
  81. if (chado_table_exists($mv_table)) {
  82. $sql = 'DROP TABLE {' . $mv_table . '}';
  83. chado_query($sql);
  84. }
  85. // Create the table.
  86. chado_create_custom_table($mv_table, $mv_schema, 0, $record->mview_id, $redirect);
  87. }
  88. } catch (Exception $e) {
  89. $transaction->rollback();
  90. watchdog_exception('tripal_chado', $e);
  91. $error = _drupal_decode_exception($e);
  92. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  93. "Could not create the materialized view %table_name: %message.",
  94. ['%table_name' => $name, '%message' => $error['!message']]);
  95. return FALSE;
  96. }
  97. drupal_set_message(t("Materialized view '%name' created", ['%name' => $name]));
  98. }
  99. else {
  100. drupal_set_message(t("Materialized view, $name, already exists. Skipping creation.", ['%name' => $name]));
  101. }
  102. return TRUE;
  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 = [];
  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, [':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", ['%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, ['%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. } catch (Exception $e) {
  190. $transaction->rollback();
  191. watchdog_exception('tripal_chado', $e);
  192. $error = _drupal_decode_exception($e);
  193. drupal_set_message(t("Could not update materialized view '%table_name': %message.",
  194. ['%table_name' => $mv_table, '%message' => $error['!message']]), 'error');
  195. return FALSE;
  196. }
  197. }
  198. /**
  199. * Retrieve the materialized view_id given the name.
  200. *
  201. * @param $view_name
  202. * The name of the materialized view.
  203. *
  204. * @return
  205. * The unique identifier for the given view.
  206. *
  207. * @ingroup tripal_mviews_api
  208. */
  209. function chado_get_mview_id($view_name) {
  210. if (db_table_exists('tripal_mviews')) {
  211. $sql = "SELECT * FROM {tripal_mviews} WHERE name = :name";
  212. $results = db_query($sql, [':name' => $view_name]);
  213. $mview = $results->fetchObject();
  214. if ($mview) {
  215. return $mview->mview_id;
  216. }
  217. }
  218. return FALSE;
  219. }
  220. /**
  221. * Retrieves the list of materialized views in this site.
  222. *
  223. * @returns
  224. * An associative array where the key and value pairs are the table names.
  225. *
  226. * @ingroup tripal_mviews_api
  227. */
  228. function chado_get_mview_table_names() {
  229. $sql = "SELECT name FROM {tripal_mviews}";
  230. $resource = db_query($sql);
  231. $tables = [];
  232. foreach ($resource as $r) {
  233. $tables[$r->name] = $r->name;
  234. }
  235. asort($tables);
  236. return $tables;
  237. }
  238. /**
  239. * Populates the specified Materialized View.
  240. *
  241. * @param $mview_id
  242. * The unique ID of the materialized view for the action to be performed on.
  243. *
  244. * @ingroup tripal_mviews_api
  245. */
  246. function chado_refresh_mview($mview_id) {
  247. global $user;
  248. if (!$mview_id) {
  249. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  250. 'Must provide an mview_id when refreshing an mview.', []);
  251. return FALSE;
  252. }
  253. // Get this mview details.
  254. $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id";
  255. $results = db_query($sql, [':mview_id' => $mview_id]);
  256. $mview = $results->fetchObject();
  257. // Add a job to populate the mview.
  258. $args = ["$mview_id"];
  259. tripal_add_job("Populate materialized view '$mview->name'", 'tripal_chado',
  260. 'chado_populate_mview', $args, $user->uid);
  261. }
  262. /**
  263. * Retrieves the list of materialized view IDs and their names.
  264. *
  265. * @return
  266. * An array of objects with the following properties: mview_id, name.
  267. *
  268. * @ingroup tripal_mviews_api
  269. *
  270. */
  271. function chado_get_mviews() {
  272. $results = db_select('tripal_mviews', 'tm')
  273. ->fields('tm', ['mview_id', 'name'])
  274. ->execute();
  275. $list = [];
  276. while ($mview = $results->fetchObject()) {
  277. $list[] = $mview;
  278. }
  279. return $list;
  280. }
  281. /**
  282. * Does the specified action for the specified Materialized View.
  283. *
  284. * @param $op
  285. * The action to be taken. One of update or delete.
  286. * @param $mview_id
  287. * The unique ID of the materialized view for the action to be performed on.
  288. *
  289. * @return
  290. * TRUE if the deletion was a success, FALSE on error.
  291. *
  292. * @ingroup tripal_mviews_api
  293. */
  294. function chado_delete_mview($mview_id) {
  295. global $user;
  296. if (!$mview_id) {
  297. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  298. 'Must provide an mview_id when deleting an mview.', []);
  299. return FALSE;
  300. }
  301. try {
  302. $transaction = db_transaction();
  303. // Get this mview details.
  304. $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id";
  305. $results = db_query($sql, [':mview_id' => $mview_id]);
  306. $mview = $results->fetchObject();
  307. // If op is to delete then do so.
  308. // Remove the mview from the tripal_mviews table.
  309. $sql = "DELETE FROM {tripal_mviews} WHERE mview_id = $mview_id";
  310. db_query($sql);
  311. // Does the table already exist?
  312. $mview_exists = chado_table_exists($mview->mv_table);
  313. // Drop the table from chado if it exists.
  314. if ($mview_exists) {
  315. $sql = "DROP TABLE {" . $mview->mv_table . "}";
  316. $success = chado_query($sql);
  317. if ($success) {
  318. //unset the variable
  319. global $databases;
  320. $default_db = $databases['default']['default']['database'];
  321. $chado_schema = chado_get_schema_name('chado');
  322. if (isset($GLOBALS["chado_tables"][$default_db][$chado_schema][$mview->mv_table])) {
  323. unset($GLOBALS["chado_tables"][$default_db][$chado_schema][$mview->mv_table]);
  324. }
  325. drupal_set_message(t("Materialized view, %name, deleted.", ['%name' => $mview->name]));
  326. return TRUE;
  327. }
  328. else {
  329. drupal_set_message(t("Problem deleting materialized view, %name.", ['%name' => $mview->name]), 'error');
  330. return FALSE;
  331. }
  332. }
  333. else {
  334. return TRUE;
  335. }
  336. } catch (Exception $e) {
  337. $transaction->rollback();
  338. watchdog_exception('tripal_chado', $e);
  339. $error = _drupal_decode_exception($e);
  340. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  341. "Could not delete the materialized view %table_name: %message.",
  342. ['%table_name' => $name, '%message' => $error['!message']]);
  343. }
  344. return FALSE;
  345. }
  346. /**
  347. * Populate a Materialized View.
  348. *
  349. * @param $mview_id
  350. * The unique identifier for the materialized view to be updated.
  351. *
  352. * @return
  353. * True if successful, FALSE otherwise.
  354. *
  355. * @ingroup tripal_mviews_api
  356. */
  357. function chado_populate_mview($mview_id) {
  358. $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id ";
  359. $results = db_query($sql, [':mview_id' => $mview_id]);
  360. $mview = $results->fetchObject();
  361. if ($mview) {
  362. // Execute the query inside a transaction so that it doesn't destroy
  363. // existing data that may leave parts of the site unfunctional.
  364. $transaction = db_transaction();
  365. $previous_db = chado_set_active('chado'); // use chado database
  366. try {
  367. $success = chado_query("DELETE FROM {" . $mview->mv_table . "}");
  368. $success = chado_query("INSERT INTO {" . $mview->mv_table . "} ($mview->query)");
  369. // If success get the number of results and update the table record.
  370. if ($success) {
  371. $sql = "SELECT count(*) as cnt FROM {" . $mview->mv_table . "}";
  372. $results = chado_query($sql);
  373. $count = $results->fetchObject();
  374. $record = new stdClass();
  375. $record->mview_id = $mview_id;
  376. $record->last_update = time();
  377. $record->status = "Populated with " . number_format($count->cnt) . " rows";
  378. drupal_write_record('tripal_mviews', $record, 'mview_id');
  379. }
  380. // If not success then throw an error.
  381. else {
  382. throw new Exception("ERROR populating the materialized view " . $mview->mv_table . ". See Drupal's recent log entries for details.");
  383. }
  384. chado_set_active($previous_db);
  385. } catch (Exception $e) {
  386. $transaction->rollback();
  387. chado_set_active($previous_db);
  388. // Print and save the error message.
  389. $record = new stdClass();
  390. $record->mview_id = $mview_id;
  391. $record->status = "ERROR populating $mview->mv_table. See Drupal's recent log entries for details.\n";
  392. drupal_write_record('tripal_mviews', $record, 'mview_id');
  393. watchdog_exception('tripal_mviews', $e);
  394. return FALSE;
  395. }
  396. print "Done.\n";
  397. return TRUE;
  398. }
  399. }