Browse Source

Foreign key constraints are now created when a new custom table is added. Before the foreign key details were used for views integration and bulk loader but there were no actual FK relationships in the database. Now there are.

spficklin 12 years ago
parent
commit
b7e66e10b5
2 changed files with 29 additions and 2 deletions
  1. 4 0
      tripal_core/api/tripal_core.api.inc
  2. 25 2
      tripal_core/includes/custom_tables.php

+ 4 - 0
tripal_core/api/tripal_core.api.inc

@@ -1869,6 +1869,10 @@ function tripal_core_exclude_field_from_feature_by_default() {
  *
  * @param $sql
  *   The sql statement to execute
+ * 
+ * @returns
+ *   A database query result resource or FALSE if the query was not 
+ *   executed correctly
  */
 function chado_query($sql) {
 

+ 25 - 2
tripal_core/includes/custom_tables.php

@@ -147,10 +147,33 @@ function tripal_core_create_custom_table(&$ret, $table, $schema, $skip_creation
   }
   $success = drupal_write_record('tripal_custom_tables', $record);
   if (!$success) {
-    watchdog('tripal_core', "Error adding custom table.",
-      array('!table_name' => $table), WATCHDOG_ERROR);
+    watchdog('tripal_core', "Error adding custom table %table_name.",
+      array('%table_name' => $table), WATCHDOG_ERROR);
+    drupal_set_message(t("Could not add custom table %table_name. 
+      Please check the schema array.", array('%table_name' => $table)), 'error');      
     return FALSE;
   }
+  
+  // now add any foreign key constraints
+  if(array_key_exists('foreign keys', $schema)){
+  	$fkeys = $schema['foreign keys'];
+  	foreach ($fkeys as $fktable => $fkdetails) {
+  		$relations = $fkdetails['columns'];
+  		foreach ($relations as $left => $right) {
+  			$sql = "ALTER TABLE $table ADD CONSTRAINT " . 
+  			  $table . "_" . $left . "_fkey FOREIGN KEY ($left) REFERENCES  $fktable ($right) " .
+  			  "ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED";
+  			if(!chado_query($sql)){
+  			  watchdog('tripal_core', "Error, could not add foreign key contraint to custom table.",
+            array('!table_name' => $table), WATCHDOG_ERROR);
+			    drupal_set_message(t("Could not add foreign key contraint to table %table_name. 
+			      Please check the schema array and the report log for errors.", 
+			      array('%table_name' => $table)), 'error');      
+          return FALSE;
+  			}
+  		}
+  	}
+  }
 
   return $ret;
 }