tripal_chado.custom_tables.api.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. /**
  3. * @file
  4. * Provides an API to manage custom tables in Chado.
  5. */
  6. /**
  7. * @defgroup tripal_custom_tables_api Tripal Custom Tables API
  8. * @ingroup tripal_chado_api
  9. * @{
  10. * Provides an API to manage custom tables in Chado.
  11. * @}
  12. */
  13. /**
  14. * Edits a custom table in the chado database. It supports
  15. * using the Drupal Schema API array.
  16. *
  17. * @param $table_id
  18. * The table_id of the table to edit
  19. * @param $table_name
  20. * The name of the custom table
  21. * @param $schema
  22. * Use the Schema API array to define the custom table.
  23. * @param $skip_if_exists
  24. * Set as TRUE to skip dropping and re-creation of the table. This is
  25. * useful if the table was already created through another means and you
  26. * simply want to make Tripal aware of the table schema.
  27. *
  28. * @ingroup tripal_custom_tables_api
  29. */
  30. function chado_edit_custom_table($table_id, $table_name, $schema, $skip_if_exists = 1) {
  31. $transaction = db_transaction();
  32. try {
  33. // Create a new record
  34. $record = new stdClass();
  35. $record->table_id = $table_id;
  36. $record->table_name = $table_name;
  37. $record->schema = serialize($schema);
  38. // get the current custom table record
  39. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = :table_id";
  40. $results = db_query($sql, array(':table_id' => $table_id));
  41. $custom_table = $results->fetchObject();
  42. // if this is a materialized view then don't allow editing with this function
  43. if ($custom_table->mview_id) {
  44. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Please use the tripal_edit_mview() function to edit this custom table as it is a materialized view.", array());
  45. drupal_set_message("This custom table is a materialized view. Please use the " . l('Materialized View', 'admin/tripal/storage/chado/mviews') . " interface to edit it.", 'error');
  46. return FALSE;
  47. }
  48. // if the user changed the table name, we want to drop the old one and force
  49. // creation of the new one.
  50. if ($custom_table->table_name != $table_name) {
  51. chado_query("DROP TABLE %s", $custom_table->table_name);
  52. $skip_if_exists = 0; // we want to create the table
  53. }
  54. // if skip creation is not set, then drop the table from chado if it exists
  55. if (!$skip_if_exists) {
  56. if (db_table_exists($custom_table->table_name)) {
  57. chado_query("DROP TABLE %s", $custom_table->table_name);
  58. drupal_set_message(t("Custom Table " . $custom_table->table_name . " dropped"));
  59. }
  60. }
  61. // update the custom table record and run the create custom table function
  62. drupal_write_record('tripal_custom_tables', $record, 'table_id');
  63. $success = chado_create_custom_table ($table_name, $schema, $skip_if_exists);
  64. // Re-add the custom table to the semantic web interface to pick up any
  65. // changes in fields.
  66. tripal_add_chado_semweb_table($table_name);
  67. }
  68. catch (Exception $e) {
  69. $transaction->rollback();
  70. watchdog_exception('tripal_chado', $e);
  71. $error = _drupal_decode_exception($e);
  72. drupal_set_message(t("Could not update custom table '%table_name': %message.",
  73. array('%table_name' => $table, '%message' => $error['!message'])), 'error');
  74. return FALSE;
  75. }
  76. return TRUE;
  77. }
  78. /**
  79. * Add a new table to the Chado schema. This function is simply a wrapper for
  80. * the db_create_table() function of Drupal, but ensures the table is created
  81. * inside the Chado schema rather than the Drupal schema. If the table already
  82. * exists then it will be dropped and recreated using the schema provided.
  83. * However, it will only drop a table if it exsits in the tripal_custom_tables
  84. * table. This way the function cannot be used to accidentally alter existing
  85. * non custom tables. If $skip_if_exists is set then the table is simply
  86. * added to the tripal_custom_tables and no table is created in Chado.
  87. *
  88. * If you are creating a materialized view do not use this function, but rather
  89. * use the tripal_add_mview(). A materialized view is also considered a custom table
  90. * and an entry for it will be added to both the tripal_mviews and
  91. * tripal_custom_tables tables, but only if the tripal_add_mview() function is
  92. * used. The optional $mview_id parameters in this function is intended
  93. * for use by the tripal_add_mview() function when it calls this function
  94. * to create the table.
  95. *
  96. * @param $table
  97. * The name of the table to create.
  98. * @param $schema
  99. * A Drupal-style Schema API definition of the table
  100. * @param $skip_if_exists
  101. * Set as TRUE to skip dropping and re-creation of the table if it already
  102. * exists. This is useful if the table was already created through another
  103. * means and you simply want to make Tripal aware of the table schema. If the
  104. * table does not exist it will be created.
  105. * @param $mview_id
  106. * Optional. If this custom table is also a materialized view then provide
  107. * it's mview_id. This paramter is intended only when this function
  108. * is called by the tripal_add_mview() function. When creating a custom
  109. * table you shouldn't need to use this parameter.
  110. * @return
  111. * TRUE on success, FALSE on failure
  112. *
  113. * @ingroup tripal_custom_tables_api
  114. */
  115. function chado_create_custom_table($table, $schema, $skip_if_exists = TRUE, $mview_id = NULL) {
  116. global $databases;
  117. $created = 0;
  118. $recreated = 0;
  119. $chado_schema = tripal_get_schema_name('chado');
  120. $chado_dot = $chado_schema . '.';
  121. $transaction = db_transaction();
  122. try {
  123. // see if the table entry already exists in the tripal_custom_tables table.
  124. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = :table_name";
  125. $results = db_query($sql, array(':table_name' => $table));
  126. $centry = $results->fetchObject();
  127. // check to see if the table already exists in the chado schema
  128. $exists = chado_table_exists($table);
  129. // if the table does not exist then create it
  130. if (!$exists) {
  131. $ret = db_create_table($chado_dot . $table, $schema);
  132. $created = 1;
  133. }
  134. // if the table exists in Chado and in our custom table and
  135. // skip creation is turned off then drop and re-create the table
  136. if ($exists and is_object($centry) and !$skip_if_exists) {
  137. // drop the table we'll recreate it with the new schema
  138. chado_query('DROP TABLE {' . $table . '}');
  139. // remove any 'referring_tables' from the array as the db_create_table doesn't use that
  140. $new_schema = $schema;
  141. if (array_key_exists('referring_tables', $new_schema)) {
  142. unset($new_schema['referring_tables']);
  143. }
  144. db_create_table($chado_dot . $table, $new_schema);
  145. $recreated = 1;
  146. }
  147. // add an entry in the tripal_custom_table
  148. $record = new stdClass();
  149. $record->table_name = $table;
  150. $record->schema = serialize($schema);
  151. if ($mview_id) {
  152. $record->mview_id = $mview_id;
  153. }
  154. // if an entry already exists then remove it
  155. if ($centry) {
  156. $sql = "DELETE FROM {tripal_custom_tables} WHERE table_name = :table_name";
  157. db_query($sql, array(':table_name' => $table));
  158. }
  159. $success = drupal_write_record('tripal_custom_tables', $record);
  160. // now add any foreign key constraints
  161. if (($created or !$skip_if_exists) and array_key_exists('foreign keys', $schema)) {
  162. // iterate through the foreign keys and add each one
  163. $fkeys = $schema['foreign keys'];
  164. foreach ($fkeys as $fktable => $fkdetails) {
  165. $relations = $fkdetails['columns'];
  166. foreach ($relations as $left => $right) {
  167. $sql = '
  168. ALTER TABLE {' . $table . '}
  169. ADD CONSTRAINT ' . $table . '_' . $left . '_fkey FOREIGN KEY (' . $left . ')
  170. REFERENCES {' . $fktable . '} (' . $right . ')
  171. ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
  172. ';
  173. chado_query($sql);
  174. }
  175. }
  176. }
  177. // Add the custom table to the semantic web interface
  178. tripal_add_chado_semweb_table($table);
  179. }
  180. catch (Exception $e) {
  181. $transaction->rollback();
  182. watchdog_exception('tripal_chado', $e);
  183. $error = _drupal_decode_exception($e);
  184. drupal_set_message(t("Could not add custom table '%table_name': %message.",
  185. array('%table_name' => $table, '%message' => $error['!message'])), 'error');
  186. return FALSE;
  187. }
  188. if ($created) {
  189. drupal_set_message("Custom table, '" . $table . "' , created successfully.", 'status');
  190. }
  191. elseif ($recreated) {
  192. drupal_set_message("Custom table, '" . $table . "' , re-created successfully.", 'status');
  193. }
  194. else {
  195. drupal_set_message("Custom table, '" . $table . "' , already exists. Table structure not changed, but definition array has been saved.", 'status');
  196. }
  197. return TRUE;
  198. }
  199. /**
  200. * This function is used to validate a Drupal Schema API array prior to
  201. * passing it ot the chado_create_custom_table_schema(). This function
  202. * can be used in a form validate function or whenver a schema is provided by
  203. * a user and needs validation.
  204. *
  205. * @param $schema_array
  206. * the Drupal Schema API compatible array
  207. *
  208. * @return
  209. * An empty string for success or a message string for failure
  210. *
  211. * @ingroup tripal_custom_tables_api
  212. */
  213. function chado_validate_custom_table_schema($schema_array) {
  214. if (is_array($schema_array) and !array_key_exists('table', $schema_array)) {
  215. return "The schema array must have key named 'table'";
  216. }
  217. if (preg_match('/[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/', $schema_array['table'])) {
  218. return "Postgres will automatically change the table name to lower-case. To prevent unwanted side-effects, please rename the table with all lower-case characters.";
  219. }
  220. // check index length
  221. if (array_key_exists('indexes', $schema_array)) {
  222. foreach ($schema_array['indexes'] as $index_name => $details) {
  223. if (strlen($schema_array['table'] . '_' . $index_name) > 60) {
  224. return "One ore more index names appear to be too long. For example: '" . $schema_array['table'] . '_' . $index_name .
  225. ".' Index names are created by concatenating the table name with the index name provided " .
  226. "in the 'indexes' array of the schema. Please alter any indexes that when combined with the table name are " .
  227. "longer than 60 characters.";
  228. }
  229. }
  230. }
  231. // check unique key length
  232. if (array_key_exists('unique keys', $schema_array)) {
  233. foreach ($schema_array['unique keys'] as $index_name => $details) {
  234. if (strlen($schema_array['table'] . '_' . $index_name) > 60) {
  235. return "One ore more unique key names appear to be too long. For example: '" . $schema_array['table'] . '_' . $index_name .
  236. ".' Unique key names are created by concatenating the table name with the key name provided " .
  237. "in the 'unique keys' array of the schema. Please alter any unique keys that when combined with the table name are " .
  238. "longer than 60 characters.";
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. * Retrieve the custom table id given the name
  245. *
  246. * @param $table_name
  247. * The name of the custom table
  248. *
  249. * @return
  250. * The unique identifier for the given table
  251. *
  252. * @ingroup tripal_custom_tables_api
  253. */
  254. function chado_get_custom_table_id($table_name) {
  255. if (db_table_exists('tripal_custom_tables')) {
  256. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = :table_name";
  257. $results = db_query($sql, array(':table_name' => $table_name));
  258. $custom_table = $results->fetchObject();
  259. if ($custom_table) {
  260. return $custom_table->table_id;
  261. }
  262. }
  263. return FALSE;
  264. }
  265. /**
  266. * Retrieves the list of custom tables in this site.
  267. *
  268. * @returns
  269. * An associative array where the key and value pairs are the table names.
  270. *
  271. * @ingroup tripal_custom_tables_api
  272. */
  273. function chado_get_custom_table_names($include_mview = TRUE) {
  274. $sql = "SELECT table_name FROM {tripal_custom_tables}";
  275. if (!$include_mview) {
  276. $sql .= " WHERE mview_id IS NULL";
  277. }
  278. $resource = db_query($sql);
  279. foreach ($resource as $r) {
  280. $tables[$r->table_name] = $r->table_name;
  281. }
  282. asort($tables);
  283. return $tables;
  284. }
  285. /**
  286. * Deletes the specified custom table
  287. *
  288. * @param $table_id
  289. * The unique ID of the custom table for the action to be performed on
  290. *
  291. * @ingroup tripal_custom_tables_api
  292. */
  293. function chado_delete_custom_table($table_id) {
  294. global $user;
  295. $args = array("$table_id");
  296. if (!$table_id) {
  297. return '';
  298. }
  299. // get this table details
  300. $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = :table_id";
  301. $results = db_query($sql, array(':table_id' => $table_id));
  302. $custom_table = $results->fetchObject();
  303. // if this is a materialized view then don't allow deletion with this function
  304. if ($custom_table->mview_id) {
  305. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Please use the tripal_delete_mview() function to delete this custom table as it is a materialized view. Table not deleted.", array());
  306. drupal_set_message("This custom table is a materialized view. Please use the " . l('Materialized View', 'admin/tripal/storage/chado/mviews') . " interface to delete it.", 'error');
  307. return FALSE;
  308. }
  309. // remove the entry from the tripal_custom tables table
  310. $sql = "DELETE FROM {tripal_custom_tables} WHERE table_id = $table_id";
  311. $success = db_query($sql);
  312. if ($success) {
  313. drupal_set_message(t("Custom Table '%name' removed", array('%name' => $custom_table->table_name)));
  314. }
  315. // drop the table from chado if it exists
  316. if (chado_table_exists($custom_table->table_name)) {
  317. $success = chado_query("DROP TABLE {" . $custom_table->table_name . "}");
  318. if ($success) {
  319. drupal_set_message(t("Custom Table '%name' dropped", array('%name' => $custom_table->table_name)));
  320. }
  321. else {
  322. tripal_report_error('tripal_chado', TRIPAL_ERROR, "Cannot drop the custom table: %name", array('%name' => $custom_table->table_name));
  323. drupal_set_message(t("Cannot drop the custom table: '%name'", array('%name' => $custom_table->table_name)));
  324. }
  325. }
  326. }