tripal_chado.mviews.api.inc 15 KB

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