Bladeren bron

Continued work on migrating to Drupal 7 started on db module but still have some of the core API to do, but need other modules for testing

spficklin 11 jaren geleden
bovenliggende
commit
aee4f0f3df

+ 140 - 228
tripal_core/api/tripal_core_chado.api.inc

@@ -56,14 +56,6 @@ require_once "tripal_core.schema_v1.11.api.inc";
  *  An associative array containing the values for inserting.
  * @param $options
  *  An array of options such as:
- *  - statement_name: the name of the prepared statement to use. If the statement
- *     has not yet been prepared it will be prepared automatically. On subsequent
- *     calls with the same statement_name only an execute on the previously
- *     prepared statement will occur.
- *  - is_prepared: TRUE or FALSE. Whether or not the statement is prepared. By
- *     default if the statement is not prepared it will be automatically.
- *     However to avoid this check, which requires a database query you can
- *     set this value to true and the check will not be performed.
  *  - skip_validation: TRUE or FALSE. If TRUE will skip all the validation steps and
  *     just try to insert as is. This is much faster but results in unhandled
  *     non user-friendly errors if the insert fails.
@@ -120,12 +112,7 @@ function tripal_core_chado_insert($table, $values, $options = array()) {
   if (!is_array($options)) {
     $options = array();
   }
-  if (!array_key_exists('is_prepared', $options)) {
-    $options['is_prepared'] = FALSE;
-  }
-  if (!array_key_exists('statement_name', $options)) {
-    $options['statement_name'] = FALSE;
-  }
+
   if (!array_key_exists('skip_validation', $options)) {
     $options['skip_validation'] = FALSE;
   }
@@ -135,27 +122,6 @@ function tripal_core_chado_insert($table, $values, $options = array()) {
 
   $insert_values = array();
 
-  // Determine plan of action
-  if ($options['statement_name']) {
-    // we have a prepared statment (or want to create one) so set $prepared = TRUE
-    $prepared = TRUE;
-
-    // we need to get a persistent connection.  If one exists this function
-    // will not recreate it, but if not it will create one and store it in
-    // a Drupal variable for reuse later.
-    $connection = tripal_db_persistent_chado();
-
-    // if we cannot get a connection the abandon the prepared statement
-    if (!$connection) {
-       $prepared = FALSE;
-       unset($options['statement_name']);
-    }
-  }
-  else {
-    //print "NO STATEMENT (insert): $table\n";
-    //debug_print_backtrace();
-  }
-
   if (array_key_exists('skip_validation', $options)) {
     $validate = !$options['skip_validation'];
   }
@@ -183,17 +149,6 @@ function tripal_core_chado_insert($table, $values, $options = array()) {
     }
 
     if (is_array($value)) {
-      $foreign_options = array();
-      if ($options['statement_name']) {
-        // add the fk relationship info to the prepared statement name so that
-        // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
-        // function.
-        $fk_sname = "fk_" . $table . "_" . $field;
-        foreach ($value as $k => $v) {
-          $fk_sname .= substr($k, 0, 2);
-        }
-        $foreign_options['statement_name'] = $fk_sname;
-      }
       // select the value from the foreign key relationship for this value
       $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
 
@@ -235,12 +190,8 @@ function tripal_core_chado_insert($table, $values, $options = array()) {
             $ukselect_vals[$field] = $insert_values[$field];
           }
         }
-        // now check the constraint
-        $coptions = array();
-        if ($options['statement_name']) {
-          $coptions = array('statement_name' => 'uqsel_' . $table . '_' . $name);
-        }
-        if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals, $coptions)) {
+        // now check the constraint        
+        if (tripal_core_chado_select($table, $ukselect_cols, $ukselect_vals)) {
           watchdog('tripal_core', "tripal_core_chado_insert: Cannot insert duplicate record into $table table: " .
             print_r($values, 1), array(), 'WATCHDOG_ERROR');
           return FALSE;
@@ -283,91 +234,36 @@ function tripal_core_chado_insert($table, $values, $options = array()) {
 
   // Now build the insert SQL statement
   $ifields = array();       // contains the names of the fields
+  $itypes  = array();       // contains placeholders for the sql query
   $ivalues = array();       // contains the values of the fields
-  $itypes = array();        // contains %d/%s placeholders for the sql query
-  $iplaceholders = array(); // contains $1/$2 placeholders for the prepare query
-  $idatatypes = array();    // contains the data type of the fields (int, text, etc.)
   $i = 1;
   foreach ($insert_values as $field => $value) {
     $ifields[] = $field;
     $ivalues[":$field"] = $value;
-    $iplaceholders[] = '$' . $i;
     $i++;
     if (strcmp($value, '__NULL__')==0) {
       $itypes[] = "NULL";
-      $idatatypes[] = "NULL";
-    }
-    elseif (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
-    strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
-    strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
-      $itypes[] = "%d";
-      $idatatypes[] = 'int';
-    }
-    elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
-      $itypes[] = "%s";
-      $idatatypes[] = 'bool';
-    }
-    elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
-      $itypes[] = "%s";
-      $idatatypes[] = 'numeric';
     }
     else {
-      $itypes[] = "'%s'";
-      $idatatypes[] = 'text';
+      $itypes[] = ":$field";
     }
   }
 
   // create the SQL
   $sql = 'INSERT INTO {' . $table . '} (' . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
-
-  // if this is a prepared statement then execute it
-  if ($prepared) {
-    // if this is the first time we've run this query
-    // then we need to do the prepare, otherwise just execute
-    if ($options['is_prepared'] != TRUE) {
-      // prepare the statement
-      $psql = "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ') AS INSERT INTO {' . $table . '} (' . implode(", ", $ifields) . ") VALUES (" . implode(", ", $iplaceholders) . ")";
-      $status = tripal_core_chado_prepare($options['statement_name'], $psql, $idatatypes);
-
-      if (!$status) {
-        watchdog('tripal_core', "tripal_core_chado_insert: not able to prepare '%name' statement for: %sql", array('%name' => $options['statement_name'], '%sql' => $sql), WATCHDOG_ERROR);
-        return FALSE;
-      }
-    }
-    $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
-    $result = tripal_core_chado_execute_prepared($options['statement_name'], $sql, $ivalues);
-  }
-  // if it's not a prepared statement then insert normally
-  else {        
-    $result = chado_query($sql, $ivalues);
-  }
+  $result = chado_query($sql, $ivalues);
 
   // if we have a result then add primary keys to return array
   if ($options['return_record'] == TRUE and $result) {
     if (array_key_exists('primary key', $table_desc) and is_array($table_desc['primary key'])) {
       foreach ($table_desc['primary key'] as $field) {
-        $sql = '';
-        $psql = "PREPARE currval_" . $table . "_" . $field . " AS SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
-        $is_prepared = tripal_core_chado_prepare("currval_" . $table . "_" . $field, $psql, array());
-        $value = '';
-        if ($is_prepared) {
-           $results = db_result(chado_query("EXECUTE currval_" . $table . "_" . $field));
-           $value = $results->fetchObject();
-           if (!$value) {
-            watchdog('tripal_core', "tripal_core_chado_insert: not able to retrieve primary key after insert: %sql",
-              array('%sql' => $psql), WATCHDOG_ERROR);
-            return FALSE;
-          }
-        }
-        else {
-          $sql = "SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
-          $results =  db_result(chado_query($sql));
-          $value = $results->fetchObject();
-          if (!$value) {
-            watchdog('tripal_core', "tripal_core_chado_insert: not able to retrieve primary key after insert: %sql",
-              array('%sql' => $sql), WATCHDOG_ERROR);
-            return FALSE;
-          }
+        $sql = "SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
+        $results = chado_query($sql);
+        $value = $results->fetchObject();
+        if (!$value) {
+          watchdog('tripal_core', "tripal_core_chado_insert: not able to retrieve primary key after insert: %sql",
+            array('%sql' => $sql), WATCHDOG_ERROR);
+          return FALSE;
         }
         $values[$field] = $value;
       }
@@ -485,12 +381,14 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
   if (!is_array($options)) {
     $options = array();
   }
+/*  
   if (!array_key_exists('is_prepared', $options)) {
     $options['is_prepared'] = FALSE;
   }
   if (!array_key_exists('statement_name', $options)) {
     $options['statement_name'] = FALSE;
   }
+*/  
   if (!array_key_exists('return_record', $options)) {
     $options['return_record'] = FALSE;
   }
@@ -498,6 +396,7 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
   $update_values = array();   // contains the values to be updated
   $update_matches = array();  // contains the values for the where clause
 
+/*  
   // Determine plan of action
   if ($options['statement_name']) {
     // we have a prepared statment (or want to create one) so set $prepared = TRUE
@@ -518,6 +417,7 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
     //print "NO STATEMENT (update): $table\n";
     //debug_print_backtrace();
   }
+*/  
 
   // get the table description
   $table_desc = tripal_core_get_chado_table_schema($table);
@@ -548,6 +448,7 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
   foreach ($match as $field => $value) {
     if (is_array($value)) {
       $foreign_options = array();
+/*      
       if ($options['statement_name']) {
         // add the fk relationship info to the prepared statement name so that
         // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
@@ -558,6 +459,7 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
         }
         $foreign_options['statement_name'] = $fk_sname;
       }
+*/      
       $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
       if (sizeof($results) > 1) {
         watchdog('tripal_core', 'tripal_core_chado_update: When trying to find record to update, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
@@ -579,6 +481,7 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
     if (is_array($value)) {
       $foreign_options = array();
       // select the value from the foreign key relationship for this value
+/*      
       if ($options['statement_name']) {
         // add the fk relationship info to the prepared statement name so that
         // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
@@ -589,6 +492,7 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
         }
         $foreign_options['statement_name'] = $fk_sname;
       }
+*/      
       $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
       if (sizeof($results) > 1) {
         watchdog('tripal_core', 'tripal_core_chado_update: When trying to find update values, too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), WATCHDOG_ERROR);
@@ -749,9 +653,10 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
   $psql = drupal_substr($psql, 0, -4);  // get rid of the trailing 'AND'
 
   // finish constructing the prepared SQL statement
-  $psql =  "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
+//  $psql =  "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
 
   // finally perform the update.  If successful, return the updated record
+/*  
   if ($prepared) {
     // if this is the first time we've run this query
     // then we need to do the prepare, otherwise just execute
@@ -768,8 +673,9 @@ function tripal_core_chado_update($table, $match, $values, $options = NULL) {
   }
   // if it's not a prepared statement then insert normally
   else {
+*/  
     $result = chado_query($sql, $uargs);
-  }
+//  }
   // if we have a result then add primary keys to return array
   if ($options['return_record'] == TRUE and $result) {
     // only if we have a single result do we want to add the primary keys to the values
@@ -875,6 +781,7 @@ function tripal_core_chado_delete($table, $match, $options = NULL) {
   if (!is_array($options)) {
     $options = array();
   }
+/*  
   if (!array_key_exists('is_prepared', $options)) {
     $options['is_prepared'] = FALSE;
   }
@@ -902,7 +809,7 @@ function tripal_core_chado_delete($table, $match, $options = NULL) {
     //print "NO STATEMENT (update): $table\n";
     //debug_print_backtrace();
   }
-
+*/
   $delete_matches = array();  // contains the values for the where clause
 
   // get the table description
@@ -1024,8 +931,8 @@ function tripal_core_chado_delete($table, $match, $options = NULL) {
   $psql = drupal_substr($psql, 0, -4);  // get rid of the trailing 'AND'
 
   // finish constructing the prepared SQL statement
-  $psql =  "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
-
+//  $psql =  "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
+/*
   // finally perform the update.  If successful, return the updated record
   if ($prepared and !$void_prepared) {
     // if this is the first time we've run this query
@@ -1043,8 +950,9 @@ function tripal_core_chado_delete($table, $match, $options = NULL) {
   }
   // if it's not a prepared statement then insert normally
   else {
+*/  
     $resource = chado_query($sql, $uargs);
-  }
+//  }
 
   // finally perform the delete.  If successful, return the updated record
   $result = chado_query($sql, $dargs);
@@ -1190,18 +1098,22 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
   if (!array_key_exists('order_by', $options)) {
     $options['order_by'] = array();
   }
+/*  
   if (!array_key_exists('is_prepared', $options)) {
     $options['is_prepared'] = FALSE;
   }
+*/  
   if (!array_key_exists('return_sql', $options)) {
     $options['return_sql'] = FALSE;
   }
   if (!array_key_exists('has_record', $options)) {
     $options['has_record'] = FALSE;
   }
+/*  
   if (!array_key_exists('statement_name', $options)) {
     $options['statement_name'] = FALSE;
   }
+*/  
   if (!array_key_exists('is_duplicate', $options)) {
     $options['is_duplicate'] = FALSE;
   }
@@ -1209,7 +1121,7 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
   if (array_key_exists('pager', $options)) {
     $pager = $options['pager'];
   }
-
+/*
   // if this is a prepared statement check to see if it has already been prepared
   $prepared = FALSE;
   if ($options['statement_name']) {
@@ -1229,7 +1141,7 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
     //print "NO STATEMENT (select): $table\n";
     //debug_print_backtrace();
   }
-
+*/
   // check that our columns and values arguments are proper arrays
   if (!is_array($columns)) {
     watchdog('tripal_core', 'the $columns argument for tripal_core_chado_select must be an array.');
@@ -1356,6 +1268,7 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
           'regex_columns' => $options['regex_columns'],
 //          'case_insensitive_columns' => $options['case_insensitive_columns']
         );
+/*        
         if (array_key_exists('statement_name', $options) and $options['statement_name']) {
           // add the fk relationship info to the prepared statement name so that
           // we can prepare the selects run by the recrusive tripal_core_chado_get_foreign_key
@@ -1366,7 +1279,7 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
           }
           $foreign_options['statement_name'] = $fk_sname;
         }
-
+*/
         $results = tripal_core_chado_get_foreign_key($table_desc, $field, $value, $foreign_options);
         if (!$results or count($results)==0) {
           return array();
@@ -1409,28 +1322,25 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
     if (!empty($values)) {
       $sql .= "WHERE ";
     }
-    $psql = $sql;  // prepared SQL statement;
     $i = 1;
-    $pvalues = array();
     $itypes = array();
     foreach ($where as $field => $value) {
 
       // if we have multiple values returned then we need an 'IN' statement
       // in our where statement
       if (count($value) > 1) {
-        $sql .= "$field IN (" . db_placeholders($value, 'varchar') . ") AND ";
+        $sql .= "$field IN (";
+        $index = 0;
         foreach ($value as $v) {
-          $args[] = $v;
-          // we can't do a prepared statement with an 'IN' statement in a
-          // where clause because we can't guarantee we'll always have the
-          // same number of elements.
-          $prepared = FALSE;
+        	$sql .= ':' . $field . $index . ', ';
+          $args[':' . $field . $index] = $v;
         }
+        $sql = substr($sql, -2, 0); // remove trailing ', '
+        $sql .= ") AND ";
       }
       // if we have a null value then we need an IS NULL in our where statement
       elseif ($value === NULL) {
         $sql .= "$field IS NULL AND ";
-        $psql .= "$field IS NULL AND ";
         // Need to remove one from the argument count b/c nulls don't add an argument
         $i--;
       }
@@ -1439,108 +1349,41 @@ function tripal_core_chado_select($table, $columns, $values, $options = NULL) {
         $operator = '=';
         if (in_array($field, $options['regex_columns'])) {
           $operator = '~*';
+        }        
+        if (in_array($field, $options['case_insensitive_columns'])) {
+          $sql .= "lower($field) $operator lower(:$field) AND ";
+          $args[":$field"] = $value[0];
         }
-
-        // get the types for the prepared statement. First check if the type
-        // is an integer
-        if (strcasecmp($table_desc['fields'][$field]['type'], 'serial')==0 OR
-            strcasecmp($table_desc['fields'][$field]['type'], 'int')==0 OR
-            strcasecmp($table_desc['fields'][$field]['type'], 'integer')==0) {
-          $sql .= "$field $operator %d AND ";
-          $psql .= "$field $operator \$" . $i . " AND ";
-          $args[] = $value[0];
-          // set the variables needed for the prepared statement
-          $idatatypes[] = 'int';
-          $itypes[] = '%d';
-          $pvalues[] = $value[0];
-        }
-        elseif (strcasecmp($table_desc['fields'][$field]['type'], 'boolean')==0) {
-          $sql .= "$field $operator %s AND ";
-          $psql .= "$field $operator \$" . $i . " AND ";
-          $args[] = $value[0];
-          // set the variables needed for the prepared statement
-          $idatatypes[] = 'bool';
-          $itypes[] = '%d';
-          $pvalues[] = $value[0];
-        }
-        elseif (strcasecmp($table_desc['fields'][$field]['type'], 'float')==0) {
-          $sql .= "$field $operator %s AND ";
-          $psql .= "$field $operator \$" . $i . " AND ";
-          $args[] = $value[0];
-          // set the variables needed for the prepared statement
-          $idatatypes[] = 'numeric';
-          $itypes[] = '%f';
-          $pvalues[] = $value[0];
-        }
-        // else the type is a text
         else {
-          if (in_array($field, $options['case_insensitive_columns'])) {
-            $sql .= "lower($field) $operator lower('%s') AND ";
-            $psql .= "lower($field) $operator lower(\$" . $i . ") AND ";
-            $args[] = $value[0];
-          }
-          else {
-            $sql .= "$field $operator '%s' AND ";
-            $psql .= "$field $operator \$" . $i . " AND ";
-            $args[] = $value[0];
-          }
-          // set the variables needed for the prepared statement
-          $idatatypes[] = 'text';
-          $itypes[] = "'%s'";
-          $pvalues[] = $value[0];
+	        $sql .= "$field $operator :$field AND ";
+	        $args[":$field"] = $value[0];        	
         }
       }
       $i++;
     } // end foreach item in where clause
     $sql = drupal_substr($sql, 0, -4);  // get rid of the trailing 'AND '
-    $psql = drupal_substr($psql, 0, -4);  // get rid of the trailing 'AND '
-
   } // end if (empty($where)){ } else {
 
   // finally add any ordering of the results to the SQL statement
   if (count($options['order_by']) > 0) {
     $sql .= " ORDER BY ";
-    $psql .= " ORDER BY ";
     foreach ($options['order_by'] as $field => $dir) {
       $sql .= "$field $dir, ";
-      $psql .= "$field $dir, ";
     }
     $sql = drupal_substr($sql, 0, -2);  // get rid of the trailing ', '
-    $psql = drupal_substr($psql, 0, -2);  // get rid of the trailing ', '
   }
-
-  // finish constructing the prepared SQL statement
-  if ($options['statement_name']) {
-    $psql =  "PREPARE " . $options['statement_name'] . " (" . implode(', ', $idatatypes) . ") AS " . $psql;
-  }
-
+  
   // if the caller has requested the SQL rather than the results...
   // which happens in the case of wanting to use the Drupal pager, then do so
   if ($options['return_sql'] == TRUE) {
     return array('sql' => $sql, 'args' => $args);
   }
-
-  // prepare the statement
-  if ($prepared) {
-    // if this is the first time we've run this query
-    // then we need to do the prepare, otherwise just execute
-    if ($options['is_prepared'] != TRUE) {
-      $status = tripal_core_chado_prepare($options['statement_name'], $psql, $idatatypes);
-      if (!$status) {
-        return FALSE;
-      }
-    }
-    $sql = "EXECUTE " . $options['statement_name'] . "(" . implode(", ", $itypes) . ")";
-    // TODO: make the pager option work with prepared queries.
-    $resource = tripal_core_chado_execute_prepared($options['statement_name'], $sql, $pvalues);
+ 
+  if (array_key_exists('limit', $pager)) {
+    $resource = chado_pager_query($sql, $pager['limit'], $pager['element'], NULL, $args);
   }
   else {
-    if (array_key_exists('limit', $pager)) {
-      $resource = chado_pager_query($sql, $pager['limit'], $pager['element'], NULL, $args);
-    }
-    else {
-      $resource = chado_query($sql, $args);
-    }
+    $resource = chado_query($sql, $args);
   }
 
   // format results into an array
@@ -2147,9 +1990,11 @@ function tripal_core_expand_chado_vars($object, $type, $to_expand, $table_option
           // if a prepared statement is provided generate a new statement_name so that
           // we don't conflict when we recurse.
           $new_options = $table_options;
+/*          
           if (array_key_exists('statement_name', $table_options)) {
              $new_options['statement_name'] = "exp_" . $foreign_table . "_" . substr($left, 0, 2) . substr($right, 0, 2);
           }
+*/          
           $foreign_object = tripal_core_generate_chado_var($foreign_table, array($left => $object->{$right}), $new_options);
 
           // if the generation of the object was successful, update the base object to include it.
@@ -2443,9 +2288,9 @@ function chado_query($sql, $args = array()) {
   // if Chado is not local to the Drupal database then we have to 
   // switch to another database
   else {
-    $previous_db = db_set_active('chado') ;
+    $previous_db = tripal_db_set_active('chado') ;
     $results = db_query($sql);
-    db_set_active($previous_db);
+    tripal_db_set_active($previous_db);
   }
   
   return $results;
@@ -2822,6 +2667,7 @@ function tripal_core_delete_property_by_id($basetable, $record_id) {
  *   TRUE if the statement is preapred, FALSE otherwise
  */
 function tripal_core_is_sql_prepared($statement_name) {
+/*	
   global $_tripal_core_prepared_statements;
 
   if (!is_array($_tripal_core_prepared_statements)) {
@@ -2843,6 +2689,7 @@ function tripal_core_is_sql_prepared($statement_name) {
     return TRUE;
   }
   return FALSE;
+*/  
 }
 
 /**
@@ -2859,6 +2706,7 @@ function tripal_core_is_sql_prepared($statement_name) {
  *   be the type of value needed (ie: text, int, etc.)
  */
 function tripal_core_chado_prepare($statement_name, $psql, $args) {
+/*	
   global $_tripal_core_persistent_chado;
   global $_tripal_core_prepared_statements;
 
@@ -2897,6 +2745,7 @@ function tripal_core_chado_prepare($statement_name, $psql, $args) {
     $_tripal_core_prepared_statements[$statement_name]['prepared_sql'] = $psql;
     return TRUE;
   }
+*/  
 }
 
 /**
@@ -2911,6 +2760,7 @@ function tripal_core_chado_prepare($statement_name, $psql, $args) {
  *   An array of values in the execute sql statement
  */
 function tripal_core_chado_execute_prepared($statement_name, $sql, $values) {
+/*	
   global $_tripal_core_prepared_statements;
 
   if (!tripal_core_is_sql_prepared($statement_name)) {
@@ -2934,13 +2784,7 @@ function tripal_core_chado_execute_prepared($statement_name, $sql, $values) {
           case 'text':
             // anything can be converted to a string, so if the type is 'text' let's just convert it
             $values[$k] = (string) $v;
-            /*
-            $check = is_string($v);
-            if ($v != '' and !$check) {
-              watchdog('tripal_core', "chado_execute_prepared: wrong argument type supplied for '%name' statement, field %k. Expected %required but recieved '%value'",
-                array('%name' => $statement_name, '%k' => $k+1, '%required' => $required_values[$k], '%value' => print_r($v, TRUE)), WATCHDOG_ERROR);
-              return FALSE;
-            } */
+
             break;
           case 'int':
             $check = is_numeric($v);
@@ -2990,8 +2834,10 @@ function tripal_core_chado_execute_prepared($statement_name, $sql, $values) {
         '%values' => print_r($values, TRUE), '%statement' => $_tripal_core_prepared_statements[$statement_name]['prepared_sql']), WATCHDOG_ERROR);
     return FALSE;
   }
+  */
 }
 
+
 /**
  * Clears prepared statements to avoid conflicts
  *
@@ -2999,6 +2845,7 @@ function tripal_core_chado_execute_prepared($statement_name, $sql, $values) {
  * Otherwise, it clears prepared statement names that match the regex provided
  */
 function tripal_core_chado_clear_prepared($statement_name_regex = NULL) {
+/*	
   global $_tripal_core_prepared_statements;
 
   if ($statement_name_regex) {
@@ -3014,6 +2861,7 @@ function tripal_core_chado_clear_prepared($statement_name_regex = NULL) {
     $_tripal_core_prepared_statements = array();
     chado_query('DEALLOCATE PREPARE ALL');
   }
+  */
 }
 
 /**
@@ -3027,6 +2875,7 @@ function tripal_core_chado_clear_prepared($statement_name_regex = NULL) {
  *   A postgresql connection object which can be used by pg_prepare, pg_execute, etc.
  */
 function tripal_db_persistent_chado() {
+/*	
   global $db_url;
   global $_tripal_core_persistent_chado;
 
@@ -3060,25 +2909,27 @@ function tripal_db_persistent_chado() {
     return $connection;
   }
   return FALSE;
+  */
 }
 
 /**
  * Release a persistent chado connection
  */
 function tripal_db_release_persistent_chado() {
-  $_tripal_core_persistent_chado = NULL;
+//  $_tripal_core_persistent_chado = NULL;
 }
 
 /**
  * Start a transaction block. Ensures the use of a persistent chado connection
  */
 function tripal_db_start_transaction() {
-  $connection = tripal_db_persistent_chado();
+/*  $connection = tripal_db_persistent_chado();
   if ($connection) {
     chado_query("BEGIN");
     return $connection;
   }
   return FALSE;
+*/
 }
 
 /**
@@ -3156,6 +3007,34 @@ function tripal_get_chado_custom_schema($table) {
   }
 }
 
+/**
+ * Check that any given Chado table exists.  This function
+ * is necessary because Drupa's db_table_exists function
+ * hardcodes the 'public'
+ *
+ * @return
+ *   TRUE/FALSE depending upon whether it exists
+ */
+function tripal_chado_table_exists($table) {
+	global $databases;
+	
+	$default_db = $databases['default']['default']['database'];
+
+  $sql = "
+    SELECT 1
+    FROM information_schema.tables 
+    WHERE 
+      table_name = :table_name AND 
+      table_schema = 'chado' AND 
+      table_catalog = '$default_db' 
+  ";
+  $results = db_query($sql, array(':table_name' => $table));
+  $exists = $results->fetchObject();
+  if (!$exists) {
+  	return FALSE;
+  }
+  return TRUE;
+}
 /**
  * Check that the Chado schema exists within the local database
  *
@@ -3288,9 +3167,9 @@ function tripal_core_set_chado_version() {
       // return uninstalled as the version
       return 'not installed';
     }
-    $previous_db = db_set_active('chado');
+    $previous_db = tripal_db_set_active('chado');
     $prop_exists = db_table_exists('chadoprop');
-    db_set_active($previous_db);
+    tripal_db_set_active($previous_db);
   }
   else {
   	$is_local = 1;
@@ -3311,9 +3190,9 @@ function tripal_core_set_chado_version() {
     WHERE CV.name = 'chado_properties' and CVT.name = 'version'
   ";
   if (!$is_local) {
-	  $previous_db = db_set_active('chado');
+	  $previous_db = tripal_db_set_active('chado');
 	  $results = db_query($sql);
-	  db_set_active($previous_db);
+	  tripal_db_set_active($previous_db);
   }
   else {
     $results = chado_query($sql);
@@ -3588,3 +3467,36 @@ function tripal_core_is_tripal_node_type($chado_table) {
     return FALSE;
   }
 }
+
+/**
+ * Set the Tripal Database
+ *
+ * The tripal_db_set_active function is used to prevent namespace collisions
+ * when chado and drupal are installed in the same database but in different
+ * schemas.  It is also used for backwards compatibility with older versions
+ * of tripal or in cases where chado is located outside of the Drupal database.
+ * or when using Drupal functions such as db_table_exists()
+ *
+ * @ingroup tripal_chado_api
+ */
+function tripal_db_set_active($dbname  = 'default') {
+  global $databases, $active_db;
+  
+  $chado_exists = variable_get('chado_schema_exists', FALSE);
+  if ($chado_exists) {
+    if($dbname == 'chado') {
+      db_query('set search_path to chado');
+      return 'default';
+    }
+    else {
+      db_query('set search_path to public');
+      return 'chado';
+    }
+  }
+  // if the 'chado' database is in the $db_url variable then chado is
+  // not in the same Drupal database, so we don't need to set any
+  // search_path and can just change the database
+  elseif (array_key_exists($dbname, $databases)) {
+    return db_set_active($dbname);
+  }
+}

+ 68 - 37
tripal_core/api/tripal_core_custom_tables.api.inc

@@ -66,7 +66,7 @@ function tripal_core_edit_custom_table($table_id, $table_name, $schema, $skip_cr
       }
 
       // re-create the table
-      if (!tripal_core_create_custom_table ($ret, $table_name, $schema)) {
+      if (!tripal_core_create_custom_table ($table_name, $schema)) {
         drupal_set_message(t("Could not create the custom table. Check Drupal error report logs."));
       }
       else {
@@ -87,8 +87,6 @@ function tripal_core_edit_custom_table($table_id, $table_name, $schema, $skip_cr
  * non custom tables.  If $skip_creation is set then the table is simply
  * added to the tripal_custom_tables and no table is created in Chado.
  *
- * @param $ret
- *   Array to which query results will be added.
  * @param $table
  *   The name of the table to create.
  * @param $schema
@@ -100,45 +98,61 @@ function tripal_core_edit_custom_table($table_id, $table_name, $schema, $skip_cr
  *   table does not exist it will be created.
  *
  * @return
- *   A database query result resource for the new table, or FALSE if table was not constructed.
+ *   TRUE on success, FALSE on failure
  *
  * @ingroup tripal_custom_tables_api
  */
-function tripal_core_create_custom_table(&$ret, $table, $schema, $skip_creation = 1) {
-  $ret = array();
-      
+function tripal_core_create_custom_table($table, $schema, $skip_creation = 1) {
+	global $databases;
+	$created = 0;
+	$recreated = 0;
+	
   // see if the table entry already exists in the tripal_custom_tables table.
   $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_name = :table_name";
   $results = db_query($sql, array(':table_name' => $table));
   $centry = $results->fetchObject();
   
-  // check to see if the table already exists in the chado schema  
-  $previous_db = db_set_active('chado');  // use chado database
-  $exists = db_table_exists($table);
-  db_set_active($previous_db);  // now use drupal database
-
+  // check to see if the table already exists in the chado schema
+  $exists = tripal_chado_table_exists($table); 
   
   // if the table does not exist then create it
-  if (!$exists) {
-    $previous_db = db_set_active('chado');  // use chado database
-    db_create_table($ret, $table, $schema);
-    db_set_active($previous_db);  // now use drupal database
-    if (count($ret)==0) {
-      watchdog('tripal_core', "Error adding custom table '!table_name'.",
-        array('!table_name' => $table), WATCHDOG_ERROR);
-      return FALSE;
+  if (!$exists) { 
+  	$previous_db = tripal_db_set_active('chado');  // use chado database   
+    try {    	
+      $ret = db_create_table($table, $schema);
+      tripal_db_set_active($previous_db);  // now use drupal database
+      $created = 1;
     }
+    catch (Exception $e) {
+    	tripal_db_set_active($previous_db);  // now use drupal database
+    	$error = $e->getMessage();
+      watchdog('tripal_core', "Error adding custom table: @message",
+        array('@message' => $error), WATCHDOG_ERROR);
+      drupal_set_message("Could not add custom table. $error.", "error");
+      return FALSE;
+    }    
   }  
 
   // if the table exists in Chado and in our custom table and
   // skip creation is turned off then drop and re-create the table 
   if ($exists and is_object($centry) and !$skip_creation) {    
     
-    // drop the table we'll recreate it with the new schema
-    $previous_db = db_set_active('chado');  // use chado database
-    db_drop_table($ret, $table);
-    db_create_table($ret, $table, $schema);
-    db_set_active($previous_db);  // now use drupal database
+    // drop the table we'll recreate it with the new schema    
+    try {	    
+	    chado_query('DROP TABLE {' . $table . '}');
+	    $previous_db = tripal_db_set_active('chado');  // use chado database
+	    db_create_table($table, $schema);
+	    tripal_db_set_active($previous_db);  // now use drupal database    
+	    $recreated = 1;
+    }
+    catch (Exception $e) {
+      tripal_db_set_active('default');  // now use drupal database
+      $error = $e->getMessage();
+      watchdog('tripal_core', "Error adding custom table: @message",
+        array('@message' => $error), WATCHDOG_ERROR);
+      drupal_set_message("Could not add custom table. $error.", "error");
+      return FALSE;
+    }
   }
 
   // add an entry in the tripal_custom_table
@@ -160,27 +174,44 @@ function tripal_core_create_custom_table(&$ret, $table, $schema, $skip_creation
     return FALSE;
   }
   
+  
   // now add any foreign key constraints
   if (!$skip_creation and array_key_exists('foreign keys', $schema)) {
+    
+    // iterate through the foreign keys and add each one
     $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;
+        $sql = '
+          ALTER TABLE {' . $table . '} 
+            ADD CONSTRAINT ' . $table . '_' . $left . '_fkey FOREIGN KEY (' . $left . ') 
+            REFERENCES  {' . $fktable . '} (' . $right . ') 
+            ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
+        ';
+        try {
+          chado_query($sql);
+        }
+        catch (Exception $e) {
+        	$error = $e->getMessage();
+          watchdog('tripal_core', "Error, could not add foreign key contraint to custom table: %error",
+            array('%error' => $error), WATCHDOG_ERROR);
+          drupal_set_message("Could not add foreign key contraint to table: $error", 'error');      
+          return FALSE;        	
         }
       }
     }
   }
-
+  
+  if ($created) {
+    drupal_set_message("Custom table created successfully.", 'status');
+  }
+  elseif ($recreated) {
+  	drupal_set_message("Custom table re-created successfully.", 'status');
+  }
+  else {
+  	drupal_set_message("Custom table already exists. Table structure not changed, but definition array has been saved.", 'status');
+  }
   return TRUE;
 }
 /**
@@ -205,4 +236,4 @@ function tripal_custom_tables_get_table_id($table_name) {
   }
 
   return FALSE;
-}
+}

+ 1 - 1
tripal_core/api/tripal_core_files.api.inc

@@ -47,7 +47,7 @@ function tripal_create_moddir($module_name) {
 
   // make the data directory for this module
   $data_dir = tripal_file_directory_path() . "$module_name";
-  if (!file_check_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
+  if (!file_prepare_directory($data_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
     $message = "Cannot create directory $data_dir. This module may not " .
                "behave correctly without this directory.  Please  create " .
                "the directory manually or fix the problem and reinstall.";

+ 1 - 1
tripal_core/api/tripal_core_jobs.api.inc

@@ -209,7 +209,7 @@ function tripal_jobs_rerun($job_id, $goto_jobs_page = TRUE) {
 function tripal_jobs_cancel($job_id, $redirect = TRUE) {
   $sql = "SELECT * FROM {tripal_jobs} WHERE job_id = :job_id";
   $results = db_query($sql, array(':job_id' => $job_id));
-  $job = $results->fetchOjbect();
+  $job = $results->fetchObject();
 
   // set the end time for this job
   if ($job->start_time == 0) {

+ 12 - 12
tripal_core/api/tripal_core_mviews.api.inc

@@ -78,12 +78,12 @@ function tripal_add_mview($name, $modulename, $mv_table, $mv_specs, $indexed,
   if (drupal_write_record('tripal_mviews', $record)) {
 
     // drop the table from chado if it exists
-    $previous_db = db_set_active('chado');  // use chado database
+    $previous_db = tripal_db_set_active('chado');  // use chado database
     if (db_table_exists($mv_table)) {
       $sql = "DROP TABLE $mv_table";
       db_query($sql);
     }
-    db_set_active($previous_db);  // now use drupal database
+    tripal_db_set_active($previous_db);  // now use drupal database
 
     // now construct the indexes
     $index = '';
@@ -100,7 +100,7 @@ function tripal_add_mview($name, $modulename, $mv_table, $mv_specs, $indexed,
     // create the table differently depending on if it the traditional method
     // or the Drupal Schema API method
     if ($mv_schema) {
-      if (!tripal_core_create_custom_table ($ret, $mv_table, $schema_arr, 0)) {
+      if (!tripal_core_create_custom_table ($mv_table, $schema_arr, 0)) {
         drupal_set_message(t("Could not create the materialized view. Check Drupal error report logs."), 'error');
       }
       else {
@@ -110,9 +110,9 @@ function tripal_add_mview($name, $modulename, $mv_table, $mv_specs, $indexed,
     else {
       // add the table to the database
       $sql = "CREATE TABLE {$mv_table} ($mv_specs); $index";
-      $previous_db = db_set_active('chado');  // use chado database
+      $previous_db = tripal_db_set_active('chado');  // use chado database
       $results = db_query($sql);
-      db_set_active($previous_db);  // now use drupal database
+      tripal_db_set_active($previous_db);  // now use drupal database
       if ($results) {
         drupal_set_message(t("View '%name' created", array('%name' => $name)));
       }
@@ -199,13 +199,13 @@ function tripal_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
   
   // if we are going to create the table then we must first drop it if it exists
   if ($create_table) {
-    $previous_db = db_set_active('chado');  // use chado database
+    $previous_db = tripal_db_set_active('chado');  // use chado database
     if (db_table_exists($mview->mv_table)) {
       $sql = "DROP TABLE :table_name";
       db_query($sql, array(':table_name' => $mview->mv_table));
       drupal_set_message(t("View '%name' dropped", array('%name' => $name)));
     }
-    db_set_active($previous_db);  // now use drupal database
+    tripal_db_set_active($previous_db);  // now use drupal database
   }
 
   // update the record to the tripal_mviews table and if successful
@@ -226,7 +226,7 @@ function tripal_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
     // re-create the table differently depending on if it the traditional method
     // or the Drupal Schema API method
     if ($create_table and $mv_schema) {     
-      if (!tripal_core_create_custom_table($ret, $mv_table, $schema_arr, 0)) {
+      if (!tripal_core_create_custom_table($mv_table, $schema_arr, 0)) {
         drupal_set_message(t("Could not create the materialized view. Check Drupal error report logs."));
       }
       else {
@@ -319,12 +319,12 @@ function tripal_mviews_action($op, $mview_id, $redirect = FALSE) {
            "WHERE mview_id = $mview_id";
     db_query($sql);
     // drop the table from chado if it exists
-    $previous_db = db_set_active('chado');  // use chado database
+    $previous_db = tripal_db_set_active('chado');  // use chado database
     if (db_table_exists($mview->mv_table)) {
       $sql = "DROP TABLE $mview->mv_table";
       db_query($sql);
     }
-    db_set_active($previous_db);  // now use drupal database
+    tripal_db_set_active($previous_db);  // now use drupal database
   }
 
   // Redirect the user
@@ -352,10 +352,10 @@ function tripal_update_mview($mview_id) {
     // execute the query inside a transaction so that it doesn't destroy existing data
     // that may leave parts of the site unfunctional
     tripal_db_start_transaction();
-    $previous_db = db_set_active('chado');  // use chado database
+    $previous_db = tripal_db_set_active('chado');  // use chado database
     $results = db_query("DELETE FROM {" . $mview->mv_table . "}");
     $results = db_query("INSERT INTO {" . $mview->mv_table . "} ($mview->query)");    
-    db_set_active($previous_db);  // now use drupal database
+    tripal_db_set_active($previous_db);  // now use drupal database
     if ($results) {
       // commit the transaction
       tripal_db_commit_transaction();

+ 4 - 6
tripal_core/includes/chado_install.inc

@@ -363,13 +363,11 @@ function tripal_core_install_sql($sql_file) {
         $query = preg_replace("/public/m", "chado", $query);
       }
       
-      if (!$chado_local) {
-        $previous = db_set_active('chado');
-      }
+      
+      $previous = tripal_db_set_active('chado');
       $result = db_query($query);
-      if (!$chado_local) {
-        db_set_active($previous);
-      }
+      tripal_db_set_active($previous);
+
       if (!$result) {
         $error  = pg_last_error();
         print "FAILED. Line  $i, $in_string\n$error:\n$query\n\n";        

+ 29 - 10
tripal_core/includes/custom_tables.inc

@@ -8,6 +8,14 @@
  * @ingroup tripal_core
  */
 
+/**
+ * 
+ */
+function tripal_custom_table_new_page() {
+	$output = drupal_render(drupal_get_form('tripal_custom_tables_form'));
+	return $output;   	
+	
+}
 /**
  * A template function which returns markup to display details for the custom table
  *
@@ -84,8 +92,17 @@ function tripal_custom_tables_list() {
         'colspan' => 6),
     )
   );
+  $table = array(
+    'header' => $header, 
+    'rows' => $rows, 
+    'attributes' => array(), 
+    'sticky' => FALSE,
+    'caption' => '',
+    'colgroups' => array(), 
+    'empty' => 'No custom tables have been added', 
+  );
 
-  $page = theme('table', $header, $rows);
+  $page = theme_table($table);  
   return $page;
 }
 
@@ -102,7 +119,7 @@ function tripal_custom_tables_list() {
  *
  * @ingroup tripal_core
  */
-function tripal_custom_tables_form(&$form_state = NULL, $table_id = NULL) {
+function tripal_custom_tables_form($form, &$form_state = NULL, $table_id = NULL) {
 
   if (!$table_id) {
     $action = 'Add';
@@ -112,6 +129,8 @@ function tripal_custom_tables_form(&$form_state = NULL, $table_id = NULL) {
   }
 
   // get this requested table
+  $default_schema = '';
+  $default_force_drop = 0;
   if (strcmp($action, 'Edit')==0) {
     $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = :table_id ";
     $results = db_query($sql, array(':table_id' => $table_id));
@@ -144,8 +163,8 @@ function tripal_custom_tables_form(&$form_state = NULL, $table_id = NULL) {
   );
   
   $form['instructions']= array(
-    '#type'          => 'markup',
-    '#value'         => t('At times it is necessary to add a custom table to the Chado schema.  
+    '#type'          => 'item',
+    '#description'         => t('At times it is necessary to add a custom table to the Chado schema.  
        These are not offically sanctioned tables but may be necessary for local data requirements.  
        Avoid creating custom tables when possible as other GMOD tools may not recognize these tables
        nor the data in them.  Linker tables or property tables are often a good candidate for
@@ -185,13 +204,13 @@ function tripal_custom_tables_form(&$form_state = NULL, $table_id = NULL) {
   $form['#redirect'] = 'admin/tripal/custom_tables';
   
   $form['example']= array(
-    '#type'          => 'markup',
-    '#value'         => "<br>Example library_stock table: <pre>
+    '#type'          => 'item',
+    '#description'         => "<br>Example library_stock table: <pre>
 array (
   'table' => 'library_stock',
   'fields' => array (
     'library_stock_id' => array(
-      'type' => serial,
+      'type' => 'serial',
       'not null' => TRUE,
     ),
     'library_id' => array(
@@ -277,9 +296,9 @@ function tripal_custom_tables_form_validate($form, &$form_state) {
         $results = db_query($sql, array(':table_id' => $table_id));
         $ct = $results->fetchObject();
         if ($ct->table_name != $schema_array['table']) {
-          $previous_db = db_set_active('chado');
+          $previous_db = tripal_db_set_active('chado');
           $exists = db_table_exists($schema_array['table']);
-          db_set_active($previous_db);        
+          tripal_db_set_active($previous_db);        
           if ($exists) {
             form_set_error($form_state['values']['schema'],
               t("The table name already exists, please choose a different name."));  
@@ -318,7 +337,7 @@ function tripal_custom_tables_form_submit($form, &$form_state) {
     tripal_core_edit_custom_table($table_id, $schema_arr['table'], $schema_arr, $skip_creation);
   }
   elseif (strcmp($action, 'Add') == 0) {
-    tripal_core_create_custom_table($ret, $schema_arr['table'], $schema_arr, $skip_creation);
+    tripal_core_create_custom_table($schema_arr['table'], $schema_arr, $skip_creation);
   }
   else {
     drupal_set_message(t("No action performed."));

+ 46 - 19
tripal_core/includes/jobs.inc

@@ -190,22 +190,8 @@ function tripal_jobs_report() {
  *   The HTML describing the indicated job
  * @ingroup tripal_core
  */
-function tripal_jobs_view($job_id) {
-  return theme('tripal_core_job_view', $job_id);
-}
-
-/**
- * Registers variables for the tripal_core_job_view themeing function
- *
- * @param $variables
- *   An array containing all variables supplied to this template
- *
- * @ingroup tripal_core
- */
-function tripal_core_preprocess_tripal_core_job_view(&$variables) {
-
+function tripal_jobs_view($job_id) { 
   // get the job record
-  $job_id = $variables['job_id'];
   $sql =
     "SELECT TJ.job_id,TJ.uid,TJ.job_name,TJ.modulename,TJ.progress,
             TJ.status as job_status, TJ,submit_date,TJ.start_time,
@@ -236,14 +222,55 @@ function tripal_core_preprocess_tripal_core_job_view(&$variables) {
   else {
     $job->arguments = $args;
   }
-
+  // generate the list of arguments for display
+  $arguments = '';  
+  foreach ($job->arguments as $key => $value) {
+     $arguments .= "$key: $value<br>";
+  } 
+  
+  // build the links
+  $links  = l('Return to jobs list', "admin/tripal/tripal_jobs/") . ' | ';
+  $links .= l('Re-run this job', "admin/tripal/tripal_jobs/rerun/" . $job->job_id)  . ' | ';
+  if ($job->start_time == 0 and $job->end_time == 0) {
+    $links .= l('Cancel this job', "admin/tripal/tripal_jobs/cancel/" . $job->job_id)  . ' | ';
+  }
+  
   // make our start and end times more legible
   $job->submit_date = tripal_jobs_get_submit_date($job);
   $job->start_time = tripal_jobs_get_start_time($job);
   $job->end_time = tripal_jobs_get_end_time($job);
-
-  // add the job to the variables that get exported to the template
-  $variables['job'] = $job;
+  
+  // construct the table headers
+  $header = array('Detail', 'Value');
+  
+  // construct the table rows
+  $rows[] = array('Job Description', $job->job_name);
+  $rows[] = array('Submitting Module',$job->modulename);
+  $rows[] = array('Callback function', $job->callback);
+  $rows[] = array('Arguments', $arguments);
+  $rows[] = array('Progress', $job->progress . "%");
+  $rows[] = array('Status', $job->job_status);
+  $rows[] = array('Process ID', $job->pid);
+  $rows[] = array('Submit Date', $job->submit_date);
+  $rows[] = array('Start time', $job->start_time);
+  $rows[] = array('End time', $job->end_time);
+  $rows[] = array('Error Message', $job->error_msg);
+  $rows[] = array('Priority', $job->priority);
+  $rows[] = array('Submitting User', $job->username);
+  
+  $table = array(
+    'header' => $header, 
+    'rows' => $rows, 
+    'attributes' => array(), 
+    'sticky' => FALSE,
+    'caption' => '',
+    'colgroups' => array(), 
+    'empty' => '', 
+  );  	
+  
+  $output = '<p>' . substr($links, 0, -2) . '</p>'; // remove trailing |
+  $output .= theme_table($table);
+  return $output;
 }
 
 

+ 143 - 70
tripal_core/includes/mviews.inc

@@ -25,8 +25,7 @@ function tripal_mview_report($mview_id) {
 
   // create a table with each row containig stats for
   // an individual job in the results set.
-  $return_url = url("admin/tripal/mviews/");
-  $output .= "<p><a href=\"$return_url\">Return to table of materialized views.</a></p>";
+  $output  = "<p>" . l("Return to table of materialized views", "admin/tripal/mviews/") . "</p>";
   $output .= "<p>Details for <b>$mview->name</b>:</p>";
   
   // build the URLs using the url function so we can handle installations where
@@ -56,7 +55,7 @@ function tripal_mview_report($mview_id) {
     $rows[] = array('Table Field Definitions', $mview->mv_specs);
   }
   if ($mview->query) {
-    $rows[] = array('Query', "<pre>" . $mview->query . "</pre>");
+    $rows[] = array('Query', "<textarea rows=\"15\" cols=\"120\" style=\"font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;\">" . $mview->query . "</textarea>");
   }
   if ($mview->indexed) {
     $rows[] = array('Indexed Fields', $mview->indexed);
@@ -65,10 +64,20 @@ function tripal_mview_report($mview_id) {
     $rows[] = array('Special Indexed Fields', $mview->special_index);
   }
   if ($mview->mv_schema) {
-    $rows[] = array('Drupal Schema API Definition', "<pre>" . $mview->mv_schema . "</pre>");
+    $rows[] = array('Drupal Schema API Definition', "<textarea rows=\"20\" cols=\"120\" style=\"font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;\">"  . $mview->mv_schema . "</textarea>");
   }
   
-  $table = theme_table(array(), $rows);
+  $header = array('Detail','Value');
+  $table = array(
+    'header' => $header, 
+    'rows' => $rows, 
+    'attributes' => array(), 
+    'sticky' => FALSE,
+    'caption' => '',
+    'colgroups' => array(), 
+    'empty' => 'There are no materialized views', 
+  ); 
+  $table = theme_table($table);
   $output .= $table;
 
   return $output;
@@ -123,7 +132,16 @@ function tripal_mviews_report() {
            '<li>' . t("A database transaction will be used when populating MViews. Therefore replacement of records does not occur until the query completes.  Any search forms or pages dependent on the MView will continue to function.") . '</li>' .
            '</ul></p>';
   $page .= '<b>' . t("Existing MViews") . '</b>';
-  $page .= theme('table', $header, $rows);
+  $table = array(
+    'header' => $header, 
+    'rows' => $rows, 
+    'attributes' => array(), 
+    'sticky' => FALSE,
+    'caption' => '',
+    'colgroups' => array(), 
+    'empty' => 'There are no materialized views', 
+  ); 
+  $page .= theme_table($table);
   return $page;
 }
 
@@ -140,8 +158,7 @@ function tripal_mviews_report() {
  *
  * @ingroup tripal_core
  */
-function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
-
+function tripal_mviews_form($form, &$form_state = NULL, $mview_id = NULL) {
   if (!$mview_id) {
     $action = 'Add';
   }
@@ -153,9 +170,22 @@ function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
   $schema_collapsed = 0;
   $traditional_collapsed = 1;  
   
+  $default_name = '';
+  $default_mv_table = '';
+  $default_mv_specs = '';
+  $default_indexed = '';
+  $default_mvquery = '';
+  $default_special_index = '';
+  $default_comment = '';
+  $default_modulename = '';
+  $default_schema =  '';
+  
+  // if the view is the older style legacy view then this value get's set to 1
+  $is_legacy = 0;
+  
   
   // get this requested view
-  if (strcmp($action, 'Edit')==0) {
+  if (strcmp($action, 'Edit') == 0 ) {
     $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = :mview_id ";
     $results = db_query($sql, array(':mview_id' => $mview_id));
     $mview = $results->fetchObject();
@@ -163,14 +193,16 @@ function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
     // set the default values.  If there is a value set in the
     // form_state then let's use that, otherwise, we'll pull
     // the values from the database
-    $default_name = $form_state['values']['name'];
-    $default_mv_table = $form_state['values']['mv_table'];
-    $default_mv_specs = $form_state['values']['mv_specs'];
-    $default_indexed = $form_state['values']['indexed'];
-    $default_mvquery = $form_state['values']['mvquery'];
-    $default_special_index = $form_state['values']['special_index'];
-    $default_comment = $form_state['values']['comment'];
-    $default_modulename = $form_state['values']['modulename'];
+    if (array_key_exists('values', $form_state)) {
+	    $default_name = $form_state['values']['name'];
+	    $default_mv_table = $form_state['values']['mv_table'];
+	    $default_mv_specs = $form_state['values']['mv_specs'];
+	    $default_indexed = $form_state['values']['indexed'];
+	    $default_mvquery = $form_state['values']['mvquery'];
+	    $default_special_index = $form_state['values']['special_index'];
+	    $default_comment = $form_state['values']['comment'];
+	    $default_modulename = $form_state['values']['modulename'];
+    }
 
     if (!$default_name) {
       $default_name = $mview->name;
@@ -200,6 +232,9 @@ function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
       $default_modulename = $mview->modulename ? $mview->modulename : 'tripal_core';
     }
     
+    if ($mview->mv_specs) {
+    	$is_legacy = 1;
+    }
 
     // the mv_table column of the tripal_mviews table always has the table
     // name even if it is a custom table. However, for the sake of the form,
@@ -223,6 +258,11 @@ function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
     '#value' => $action
   );
 
+  $form['is_legacy'] = array(
+    '#type' => 'value',
+    '#value' => $is_legacy
+  );
+  
   $form['mview_id'] = array(
     '#type' => 'value',
     '#value' => $mview_id
@@ -232,6 +272,12 @@ function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
     '#type' => 'value',
     '#value' => $default_modulename,
   );
+  
+  $form['return_link'] = array(
+    '#type' => 'item',
+    '#description' => l("Return to table of materialized views", "admin/tripal/mviews/"),
+  );
+  
 
   $form['name']= array(
     '#type'          => 'textfield',
@@ -267,53 +313,59 @@ function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
     '#required'      => FALSE,
     '#default_value' => $default_schema,
     '#rows'          => 25,
+    '#attributes' => array(
+      'style' => "font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;",      
+    ),
   );
 
-  // add a fieldset for the Original Table Description fields
-  $form['traditional'] = array(
-    '#type' => 'fieldset',
-    '#title' => 'Legacy MViews Setup',
-    '#description' => t('Traditionally MViews were created by specifying PostgreSQL style ' .
-                       'column types.  This method can be used but is deprecated in favor of the ' .
-                       'newer Drupal schema API method provided above. In rare cases where the Drupal Schema API ' .
-                       'does not support a desired data type the Legacy Mviews should be used'),
-    '#collapsible' => 1,
-    '#collapsed' => $traditional_collapsed,
-  );
-
-  $form['traditional']['mv_table']= array(
-    '#type'          => 'textfield',
-    '#title'         => t('Table Name'),
-    '#description'   => t('Please enter the table name that this view will generate in the database.  You can use the schema and table name for querying the view'),
-    '#required'      => FALSE,
-    '#default_value' => $default_mv_table,
-  );
-
-  $form['traditional']['mv_specs']= array(
-    '#type'          => 'textarea',
-    '#title'         => t('Table Definition'),
-    '#description'   => t('Please enter the field definitions for this view. Each field should be separated by a comma or enter each field definition on each line.'),
-    '#required'      => FALSE,
-    '#default_value' => $default_mv_specs,
-  );
-
-  $form['traditional']['indexed']= array(
-    '#type'          => 'textarea',
-    '#title'         => t('Indexed Fields'),
-    '#description'   => t('Please enter the field names (as provided in the table definition above) that will be indexed for this view.  Separate by a comma or enter each field on a new line.'),
-    '#required'      => FALSE,
-    '#default_value' => $default_indexed,
-  );
-
-  /**
-  $form['traditional']['special_index']= array(
-    '#type'          => 'textarea',
-    '#title'         => t('View Name'),
-    '#description'   => t('Please enter the name for this materialized view.'),
-    '#required'      => TRUE,
-    '#default_value' => $default_special_index,
-  );
-  */
+  // only let folks edit legacy MViews, not create new ones 
+  if ($is_legacy) {
+	  // add a fieldset for the Original Table Description fields
+	  $form['traditional'] = array(
+	    '#type' => 'fieldset',
+	    '#title' => 'Legacy MViews Setup',
+	    '#description' => t('Traditionally MViews were created by specifying PostgreSQL style ' .
+	                       'column types.  This method can be used but is deprecated in favor of the ' .
+	                       'newer Drupal schema API method provided above. In rare cases where the Drupal Schema API ' .
+	                       'does not support a desired data type the Legacy Mviews should be used'),
+	    '#collapsible' => 1,
+	    '#collapsed' => $traditional_collapsed,
+	  );
+	
+	  $form['traditional']['mv_table']= array(
+	    '#type'          => 'textfield',
+	    '#title'         => t('Table Name'),
+	    '#description'   => t('Please enter the table name that this view will generate in the database.  You can use the schema and table name for querying the view'),
+	    '#required'      => FALSE,
+	    '#default_value' => $default_mv_table,
+	  );
+	
+	  $form['traditional']['mv_specs']= array(
+	    '#type'          => 'textarea',
+	    '#title'         => t('Table Definition'),
+	    '#description'   => t('Please enter the field definitions for this view. Each field should be separated by a comma or enter each field definition on each line.'),
+	    '#required'      => FALSE,
+	    '#default_value' => $default_mv_specs,
+	  );
+	
+	  $form['traditional']['indexed']= array(
+	    '#type'          => 'textarea',
+	    '#title'         => t('Indexed Fields'),
+	    '#description'   => t('Please enter the field names (as provided in the table definition above) that will be indexed for this view.  Separate by a comma or enter each field on a new line.'),
+	    '#required'      => FALSE,
+	    '#default_value' => $default_indexed,
+	  );
+	
+	  /**
+	  $form['traditional']['special_index']= array(
+	    '#type'          => 'textarea',
+	    '#title'         => t('View Name'),
+	    '#description'   => t('Please enter the name for this materialized view.'),
+	    '#required'      => TRUE,
+	    '#default_value' => $default_special_index,
+	  );
+	  */
+  }
 
   $form['mvquery']= array(
     '#type'          => 'textarea',
@@ -322,6 +374,9 @@ function tripal_mviews_form(&$form_state = NULL, $mview_id = NULL) {
     '#required'      => TRUE,
     '#default_value' => $default_mvquery,
     '#rows'          => 25,
+    '#attributes' => array(
+      'style' => "font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;",      
+    ),
   );
 
   if ($action == 'Edit') {
@@ -351,11 +406,20 @@ function tripal_mviews_form_validate($form, &$form_state) {
   $action = $form_state['values']['action'];
   $mview_id = $form_state['values']['mview_id'];
   $name = $form_state['values']['name'];
-  $mv_table = $form_state['values']['mv_table'];
-  $mv_specs = $form_state['values']['mv_specs'];
-  $indexed = $form_state['values']['indexed'];
+  $is_legacy = $form_state['values']['is_legacy'];
   $query = $form_state['values']['mvquery'];
-  $special_index = $form_state['values']['special_index'];
+  if ($is_legacy) {
+	  $mv_table = $form_state['values']['mv_table'];
+	  $mv_specs = $form_state['values']['mv_specs'];
+	  $indexed = $form_state['values']['indexed'];	  
+	  $special_index = '';//$form_state['values']['special_index'];
+  }
+  else {
+  	$mv_table = '';
+    $mv_specs = '';
+    $indexed = '';
+    $special_index = '';
+  }
   $comment = $form_state['values']['comment'];
   $schema = $form_state['values']['schema'];
 
@@ -404,11 +468,20 @@ function tripal_mviews_form_submit($form, &$form_state) {
   $action = $form_state['values']['action'];
   $mview_id = $form_state['values']['mview_id'];
   $name = $form_state['values']['name'];
-  $mv_table = $form_state['values']['mv_table'];
-  $mv_specs = $form_state['values']['mv_specs'];
-  $indexed = $form_state['values']['indexed'];
+  $is_legacy = $form_state['values']['is_legacy'];
   $query = $form_state['values']['mvquery'];
-  $special_index = $form_state['values']['special_index'];
+  if ($is_legacy) {
+	  $mv_table = $form_state['values']['mv_table'];
+	  $mv_specs = $form_state['values']['mv_specs'];
+	  $indexed = $form_state['values']['indexed'];	  
+	  $special_index = '';//$form_state['values']['special_index'];
+  }
+  else {
+    $mv_table = '';
+    $mv_specs = '';
+    $indexed = '';
+    $special_index = '';
+  }
   $comment = $form_state['values']['comment'];
   $schema = $form_state['values']['schema'];
   $modulename = $form_state['values']['modulename'];

+ 1 - 13
tripal_core/tripal_core.module

@@ -143,13 +143,6 @@ function tripal_core_menu() {
     'page arguments' => array('tripal_core_customize'),
     'access arguments' => array('administer site configuration'),
   );
-  $items['tripal_toggle_box_menu/%/%/%'] = array(
-    'title' => 'Toggle Box',
-    'page callback' => 'tripal_toggle_box_menu',
-    'page arguments' => array(1, 2, 3),
-    'access arguments' => array('access administration pages'),
-    'type' => MENU_CALLBACK | MENU_LINKS_TO_PARENT
-  );
   $items['admin/tripal/chado_install'] = array(
     'title' => 'Install Chado Schema',
     'description' => 'Installs the Chado database tables, views, etc., inside the current Drupal database',
@@ -251,8 +244,7 @@ function tripal_core_menu() {
   $items['admin/tripal/custom_tables/new'] = array(
     'title' => 'Create Custom Table',
     'description' => 'Custom tables are added to Chado.',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_custom_tables_form'),
+    'page callback' => 'tripal_custom_table_new_page',
     'access arguments' => array('access administration pages'),
     'type' => MENU_CALLBACK,
   );
@@ -299,10 +291,6 @@ function tripal_core_permission() {
  */
 function tripal_core_theme() {
   return array(
-    'tripal_core_job_view' => array(
-      'arguments' => array('job_id' => NULL),
-      'template' => 'tripal_core_job_view',
-    ),
     'tripal_core_customize' => array(
       'arguments' => array('job_id' => NULL),
       'template' => 'tripal_core_customize',

+ 0 - 85
tripal_core/tripal_core_job_view.tpl.php

@@ -1,85 +0,0 @@
-<?php
-
-/**
- * @file
- * This is a template file to show how the details of an individual job should be displayed
- */
-
-$job = $variables['job'];
-
-$cancel_link = '';
-$return_link = url("admin/tripal/tripal_jobs/");
-if ($job->start_time == 0 and $job->end_time == 0) {
-  $cancel_link = url("admin/tripal/tripal_jobs/cancel/" . $job->job_id);
-}
-$rerun_link = url("admin/tripal/tripal_jobs/rerun/" . $job->job_id);
-
-?>
-
-<div id="tripal_core-job_view-box" class="tripal_core-info-box tripal-info-box">
-  <div class="tripal_core-info-box-title tripal-info-box-title">Details for Job <?php print $job->job_id?></div>
-  <div class="tripal_core-info-box-desc tripal-info-box-desc"></div>
-   <a href="<?php print $return_link?>">Return to jobs list</a> |
-   <a href="<?php print $rerun_link?>">Re-run this job</a> |
-   <a href="<?php print $cancel_link?>">Cancel this Job</a><br />
-   <table id="tripal_core-job_view-table" class="tripal_core-table tripal-table tripal-table-vert">
-      <tr class="tripal_core-table-odd-row tripal-table-even-row tripal-table-first-row">
-         <th>Job Description</th>
-         <td><?php print $job->job_name?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-odd-row">
-         <th>Submitting Module</th>
-         <td><?php print $job->modulename?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-even-row">
-         <th>Callback function</th>
-         <td><?php print $job->callback?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-odd-row">
-         <th>Arguments</th>
-         <td>
-           <table>
-          <?php foreach ($job->arguments as $key => $value) {
-            print "<tr><td>$key</td><td>$value</td></tr>";
-          } ?>
-           </table>
-         </td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-even-row">
-         <th>Progress</th>
-         <td><?php print $job->progress?>%</td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-odd-row">
-         <th>Status</th>
-         <td><?php print $job->job_status?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-even-row">
-         <th>Process ID</th>
-         <td><?php print $job->pid?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-odd-row">
-         <th>Submit Date</th>
-         <td><?php print $job->submit_date?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-even-row">
-         <th>Start time</th>
-         <td><?php print $job->start_time?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-odd-row">
-         <th>End time</th>
-         <td><?php print $job->end_time?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-even-row">
-         <th>Error Message</th>
-         <td><?php print $job->error_msg?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-odd-row">
-         <th>Priority</th>
-         <td><?php print $job->priority?></td>
-      </tr>
-      <tr class="tripal_core-table-odd-row tripal-table-even-row tripal-table-last-row">
-         <th>Submitting User</th>
-         <td><?php print $job->username?></td>
-      </tr>
-   </table>
-</div>

+ 195 - 155
tripal_db/includes/tripal_db.admin.inc

@@ -12,124 +12,138 @@ function tripal_db_admin_page() {
   return $output;
 }
 /**
- *
- *
- * @ingroup tripal_db
+ * 
  */
 function tripal_db_select_form() {
   return $form;
 }
-/**
- *
- * @ingroup tripal_db
- */
-function tripal_ajax_db_edit() {
-  $status = TRUE;
-
-  // prepare and render the form
-  $form = tripal_core_ahah_prepare_form();   
-  $data = drupal_render($form);  
-
-  // bind javascript events to the new objects that will be returned 
-  // so that AHAH enabled elements will work.
-  $settings = tripal_core_ahah_bind_events();
-
-  // return the updated JSON
-  drupal_json(
-    array(
-      'status'   => $status, 
-      'data'     => $data,
-      'settings' => $settings,
-    )  
-  );
-}
 
 /**
- *
+ * 
+ * @param $form
+ * @param $form_state
+ * 
  * @ingroup tripal_db
  */
-function tripal_db_form(&$form_state = NULL, $action = 'Update') {
-  
-  $dbid = $form_state['values']['dbid'];
-  
+function tripal_db_db_edit_form($form, $form_state) {
   
-  if (strcmp($action,'Update')==0) {
-    // get a list of db from chado for user to choose
-    $sql = "SELECT * FROM {db} WHERE NOT name = 'tripal' ORDER BY name ";
-    $results = chado_query($sql);
+	// get the dbid if form was submitted via AJAX
+	$dbid = 0;
+	if (array_key_exists('values', $form_state)) {
+    $dbid = $form_state['values']['dbid'];
+	}  
   
-    $dbs = array();
-    $dbs[] = '';
-    while ($db = db_fetch_object($results)) {
-      $dbs[$db->db_id] = $db->name;
-    }
+  // get a list of db from chado for user to choose
+  $sql = "SELECT * FROM {db} WHERE NOT name = 'tripal' ORDER BY name ";
+  $results = chado_query($sql);
   
-    $form['dbid'] = array(
-      '#title' => t('External Database Name'),
-      '#type' => 'select',
-      '#options' => $dbs,
-      '#ahah' => array(
-        'path' => 'admin/tripal/tripal_db/edit/js',
-        'wrapper' => 'db-edit-div',
-        'effect' => 'fade',
-        'event' => 'change',
-        'method' => 'replace',
-      ),
-      '#prefix' => '<div id="db-edit-div">',
-      '#suffix' => '</div>',
-      '#default_value' => $dbid,
-      '#description' => t('Please select a database to edit'),
-    );
-  }   
-  else {
-    $default_db = $form_state['values']['name'];
-    $default_desc = $form_state['values']['description'];
-    $default_url = $form_state['values']['url'];
-    $default_urlprefix = $form_state['values']['urlprefix']; 
+  $dbs = array();
+  $dbs[] = 'Select a database';
+  foreach ($results as $db) {
+    $dbs[$db->db_id] = $db->name;
   }
   
-  // get this requested database
+  $form['dbid'] = array(
+    '#title' => t('External Database Name'),
+    '#type' => 'select',
+    '#options' => $dbs,
+    '#ajax' => array(
+      'callback' => 'tripal_db_edit_form_ajax',
+      'wrapper'  => 'db-edit-div',
+      'effect'   => 'fade',
+      'event'    => 'change',
+      'method'   => 'replace',
+    ),
+    '#suffix' => '<div id="db-edit-div"></div>',
+    '#default_value' => $dbid,
+  );
+      
+  // if we don't have a db_id then we can safetly return the form
   if ($dbid) {
-    $values = array('db_id' => $dbid);
-    $result = tripal_core_chado_select('db', array('*'), $values);
-    $db = $result[0];
-    $prev_dbid = $form_state['values']['prev_dbid'];
-    // if the database has changed then repopulate the fields with the databaes values
-    if ($prev_dbid != $dbid) {
-      $default_db        = $db->name;
-      $default_desc      = $db->description;
-      $default_url       = $db->url;
-      $default_urlprefix = $db->urlprefix;
+  	  	
+    // if we are here because of an AJAX calback, that means the database select
+    // box was changed and the form is being rebuilt on an AJAX call not on a
+    // form validation error.  Therefore, we want to provide the dbid  
+    if (array_key_exists('triggering_element', $form_state) and 
+        $form_statte['triggerming_element']['#ajax']['callback'] = tripal_db_edit_form_ajax) {
+	    tripal_db_add_db_form_fields($form, $form_state, $dbid);
     }
-    // if the database did not change then keep the values in the form values
     else {
-      $default_db = $form_state['values']['name'];
-      $default_desc = $form_state['values']['description'];
-      $default_url = $form_state['values']['url'];
-      $default_urlprefix = $form_state['values']['urlprefix'];      
+    	tripal_db_add_db_form_fields($form, $form_state);
     }
+	  
+	  $form['update'] = array(
+	    '#type'         => 'submit',
+	    '#value'        => t('Update'),
+	    '#weight'       => 5,
+	  );
+	  $form['delete'] = array(
+	    '#type'         => 'submit',
+	    '#value'        => t('Delete'),
+      '#weight'       => 6,
+    );
   }
+  return $form;
+}
+/**
+ * 
+ * @param $form
+ * @param $form_state
+ * 
+ * @ingroup tripal_db
+ */
+function tripal_db_db_add_form($form, $form_state) {
+	
+	// add in the form fields to this form
+  tripal_db_add_db_form_fields($form, $form_state);
   
-  $form['form_action'] = array(
-    '#type' => 'hidden',
-    '#value' => $action, 
-  );  
-
-  // we need to distinguish between edits in a field that may have failed
-  // and when the user selects a different database from the list.  
-  $form['prev_dbid'] = array(
-    '#type' => 'hidden',
-    '#value' => $dbid, 
-  );  
+  $form['add'] = array(
+    '#type'         => 'submit',
+    '#value'        => t('Add'),
+    '#weight'       => 5,
+  );
+  return $form;
+}
+/**
+ * 
+ * @param $form
+ * @param $form_state
+ * @param $dbid
+ * 
+ * @ingroup tripal_db
+ */
+function tripal_db_add_db_form_fields(&$form, $form_state, $dbid = NULL) {
+	
+	$default_db        = '';
+  $default_desc      = '';
+  $default_url       = '';
+  $default_urlprefix = '';
+      
+  // get the default values from the databae first  
+  if ($dbid) {
+    $values = array('db_id' => $dbid);
+    $db = tripal_core_chado_select('db', array('*'), $values);    
+    $default_db        = $db[0]->name;
+    $default_desc      = $db[0]->description;
+    $default_url       = $db[0]->url;
+    $default_urlprefix = $db[0]->urlprefix;  
+  }    
+  // set the default value to the form_state if those exist
+  elseif (array_key_exists('values', $form_state)) {
+    $default_db        = array_key_exists('name', $form_state['values'])        ? $form_state['values']['name']        : $default_db;
+    $default_desc      = array_key_exists('description', $form_state['values']) ? $form_state['values']['description'] : $default_desc;
+    $default_url       = array_key_exists('url', $form_state['values'])         ? $form_state['values']['url']         : $default_url;
+    $default_urlprefix = array_key_exists('urlprefix', $form_state['values'])   ? $form_state['values']['urlprefix']   : $default_urlprefix;      
+  }     
+    
+  // add a fieldset for the Drupal Schema API
+  $form['fields'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'Database Details',
+    '#collapsible' => 0,
+  );    
   
-  // if we want to update a database but the user has not
-  // yet selected a database then return so we don't show the other fields
-  // the rest of the fields will be added with the AHAH callback. 
-  if (strcmp($action,'Update')==0 and !$dbid) {
-    return $form;
-  }
-
-  $form['name']= array(
+  $form['fields']['name']= array(
     '#type'          => 'textfield',
     '#title'         => t("Database Name"),
     '#description'   => t('Please enter the name for this external database.'),
@@ -139,7 +153,7 @@ function tripal_db_form(&$form_state = NULL, $action = 'Update') {
     '#maxlength'     => 255,
   );
 
-  $form['description']= array(
+  $form['fields']['description']= array(
     '#type'          => 'textarea',
     '#title'         => t('Description'),
     '#description'   => t('Please enter a description for this database'),
@@ -147,7 +161,7 @@ function tripal_db_form(&$form_state = NULL, $action = 'Update') {
     '#weight'        => 2,
     '#maxlength'     => 255,
   );
-  $form['url']= array(
+  $form['fields']['url']= array(
     '#type'          => 'textfield',
     '#title'         => t('URL'),
     '#description'   => t('Please enter the web address for this database.'),
@@ -155,7 +169,7 @@ function tripal_db_form(&$form_state = NULL, $action = 'Update') {
     '#weight'        => 3,
     '#maxlength'     => 255,
   );
-  $form['urlprefix']= array(
+  $form['fields']['urlprefix']= array(
     '#type'          => 'textfield',
     '#title'         => t('URL prefix'),
     '#description'   => t('Tripal can provide links to external databases when accession numbers or unique identifiers are known.  Typically, a database will provide a unique web address for each accession and the accession usually is the last component of the page address.  Please enter the web address, minus the accession number for this database.  When an accession number is present, Tripal will combine this web address with the accession and provide a link to the external site.'),
@@ -164,44 +178,41 @@ function tripal_db_form(&$form_state = NULL, $action = 'Update') {
     '#maxlength'     => 255,
   );
 
-
-  if (strcmp($action, 'Update')==0) {
-    $form['update'] = array(
-      '#type'         => 'submit',
-      '#value'        => t('Update'),
-      '#weight'       => 5,
-      '#executes_submit_callback' => TRUE,
-    );
-    $form['delete'] = array(
-      '#type'         => 'submit',
-      '#value'        => t('Delete'),
-      '#weight'       => 6,
-      '#executes_submit_callback' => TRUE,
-    );
-  }
-  else {
-    $form['add'] = array(
-      '#type'         => 'submit',
-      '#value'        => t('Add'),
-      '#weight'       => 5,
-      '#executes_submit_callback' => TRUE,
-    );
-  }
-
   return $form;
 }
+
 /**
- *
+ * Validation fucntion for tripal_db_db_add_form
+ * @param $form
+ * @param $form_state
+ * 
+ * @ingroup tripal_db
+ */
+function tripal_db_db_add_form_validate($form, &$form_state) {
+  tripal_db_form_fields_validate($form, $form_state); 
+}
+/**
+ * Validation fucntion for tripal_db_db_edit_form
+ * @param unknown_type $form
+ * @param unknown_type $form_state
+ * 
+ * @ingroup tripal_db
+ */
+function tripal_db_db_edit_form_validate($form, &$form_state) {
+  tripal_db_form_fields_validate($form, $form_state); 
+}
+/**
+ * Genetic validation form for shared fields of both the edit and add forms
+ * @param $form
+ * @param $form_state
+ * 
  * @ingroup tripal_db
  */
-function tripal_db_form_validate($form, &$form_state) {
+function tripal_db_form_fields_validate($form, &$form_state) {
   $name =  trim($form_state['values']['name']);
   $desc =  trim($form_state['values']['description']);
   $url  =  trim($form_state['values']['url']);
   $urlp =  trim($form_state['values']['urlprefix']);
-  $dbid =  trim($form_state['values']['dbid']);
-  $op   =  trim($form_state['values']['op']);
-  $action =  $form_state['values']['form_action'];
  
   // make sure the database name is unique
   $values = array('name' => $name);
@@ -211,10 +222,42 @@ function tripal_db_form_validate($form, &$form_state) {
   }
 }
 /**
- *
+ * 
+ * @param $form
+ * @param $form_state
+ * 
+ * @ingroup tripal_db
+ */
+function tripal_db_db_add_form_submit($form, &$form_state) {
+
+  $name =  trim($form_state['values']['name']);
+  $desc =  trim($form_state['values']['description']);
+  $url  =  trim($form_state['values']['url']);
+  $urlp =  trim($form_state['values']['urlprefix']);
+
+  $values = array(
+    'name' => $name,
+    'description' => $desc,
+    'url' => $url,
+    'urlprefix' => $urlp,
+  );
+  $success = tripal_core_chado_insert('db', $values);
+  if ($success) {
+    drupal_set_message(t("External database added"));
+  }
+  else {
+    drupal_set_message(t("Failed to add external database."));
+  }
+}
+
+/**
+ * 
+ * @param $form
+ * @param $form_state
+ * 
  * @ingroup tripal_db
  */
-function tripal_db_form_submit($form, &$form_state) {
+function tripal_db_db_edit_form_submit($form, &$form_state) {
 
   $name =  trim($form_state['values']['name']);
   $desc =  trim($form_state['values']['description']);
@@ -229,35 +272,32 @@ function tripal_db_form_submit($form, &$form_state) {
     'url' => $url,
     'urlprefix' => $urlp,
   );
-  if ($dbid) {
-    if (strcmp($op, 'Update')==0) {      
-      $match = array('db_id' => $dbid);
-      $success = tripal_core_chado_update('db', $match, $values);
-      if ($success) {
-        drupal_set_message(t("External database updated"));
-      }
-      else {
-        drupal_set_message(t("Failed to update external database."));
-      }
+  if (strcmp($op, 'Update')==0) {      
+    $match = array('db_id' => $dbid);
+    $success = tripal_core_chado_update('db', $match, $values);
+    if ($success) {
+      drupal_set_message(t("External database updated"));
     }
-    if (strcmp($op, 'Delete')==0) {
-      $match = array('db_id' => $dbid);
-      $success = tripal_core_chado_delete('db', $match);
-      if ($success) {
-        drupal_set_message(t("External database deleted"));
-      }
-      else {
-        drupal_set_message(t("Failed to delete external database."));
-      }
+    else {
+      drupal_set_message(t("Failed to update external database."));
     }
   }
-  else {
-    $success = tripal_core_chado_insert('db', $values);
+  if (strcmp($op, 'Delete')==0) {
+    $match = array('db_id' => $dbid);
+    $success = tripal_core_chado_delete('db', $match);
     if ($success) {
-      drupal_set_message(t("External database added"));
+      drupal_set_message(t("External database deleted"));
     }
     else {
-      drupal_set_message(t("Failed to add external database."));
+      drupal_set_message(t("Failed to delete external database."));
     }
   }
+}
+/**
+ * Ajax callback for the tripal_db_form
+ * @ingroup tripal_db
+ */
+function tripal_db_edit_form_ajax($form, $form_state) {
+	unset($form['dbid']);	
+  return $form;
 }

+ 2 - 2
tripal_db/tripal_db.info

@@ -1,7 +1,7 @@
 name = Tripal DB
 description = The database module for the Tripal package that integrates Drupal and GMOD chado. This module provides support for managing and viewing external databases.
-core = 6.x
+core = 7.x
 project = tripal_db
 package = Tripal
-version = 6.x-1.1
+version = 7.x-2.0
 dependencies[] = tripal_core

+ 15 - 15
tripal_db/tripal_db.module

@@ -39,7 +39,7 @@ function tripal_db_menu() {
     'title' => 'Edit a Database',
     'description' => 'Manage Databases ',
     'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_db_form', 'Update'),
+    'page arguments' => array('tripal_db_db_edit_form'),
     'access callback' => 'user_access',
     'access arguments' => array('administer db cross-references'),
     'type' => MENU_NORMAL_ITEM,
@@ -48,17 +48,12 @@ function tripal_db_menu() {
   $items['admin/tripal/tripal_db/add_db'] = array(
     'title' => 'Add a Database',
     'page callback' => 'drupal_get_form',
-    'page arguments' => array('tripal_db_form', 'Add'),
+    'page arguments' => array('tripal_db_db_add_form'),
     'access callback' => 'user_access',
     'access arguments' => array('administer db cross-references'),
     'type' => MENU_NORMAL_ITEM,
   );
-  $items['admin/tripal/tripal_db/edit/js'] = array(
-    'page callback' => 'tripal_ajax_db_edit',
-    'access callback' => 'user_access',
-    'access arguments' => array('access administration pages'),
-    'type' => MENU_CALLBACK,
-  );
+
 
   return $items;
 }
@@ -70,9 +65,12 @@ function tripal_db_menu() {
  *
  * @ingroup tripal_db
  */
-function tripal_db_perm() {
+function tripal_db_permission() {
   return array(
-    'administer db cross-references',
+    'administer db cross-references' => array(
+      'title' => t('Administer the list of external databases used for data cross-references.'),
+      'description' => t('Allows the user to add, edit or delete databases stored in the Chado database.'),
+    ),
   );
 }
 
@@ -93,11 +91,13 @@ function tripal_db_form_alter(&$form, &$form_state, $form_id) {
     // updating the form through the ahah callback sets the action of
     // the form to the ahah callback URL. We need to set it back
     // to the normal form URL 
-    if ($form_state['values']['form_action'] == 'Update') {
-      $form['#action'] = url("admin/tripal/tripal_db/edit_db");
-    }
-    if ($form_state['values']['form_action'] == 'Add') {
-      $form['#action'] = url("admin/tripal/tripal_db/add_db");
+    if (array_key_exists('values', $form_state)) {
+	    if ($form_state['values']['form_action'] == 'Update') {
+	      $form['#action'] = url("admin/tripal/tripal_db/edit_db");
+	    }
+	    if ($form_state['values']['form_action'] == 'Add') {
+	      $form['#action'] = url("admin/tripal/tripal_db/add_db");
+	    }
     }
   } 
 }

+ 1 - 3
tripal_feature/includes/tripal_feature-relationships.inc

@@ -188,15 +188,13 @@ function tripal_feature_add_ONE_relationship_form_validate($form, &$form_state)
 function tripal_feature_add_ONE_relationship_form_submit($form, &$form_state) {
 
   if ($form_state['values']['subject_id'] > 0) {
-    $previous_db = db_set_active('chado');
-    db_query(
+    chado_query(
       "INSERT INTO {stock_relationship} (subject_id, type_id, object_id, value) VALUES (%d, %d, %d, '%s')",
       $form_state['values']['subject_id'],
       $form_state['values']['type_id'],
       $form_state['values']['object_id'],
       $form_state['values']['r_description']
     );
-    db_set_active($previous_db);
 
     drupal_set_message(t('Successfully Added Relationship.'));
   } //end of insert relationship

+ 1 - 3
tripal_feature/includes/tripal_feature-secondary_tables.inc

@@ -224,12 +224,10 @@ function tripal_feature_is_obsolete_form($node, $stock_id) {
  */
 function tripal_feature_is_obsolete_form_submit($form, &$form_state) {
 
-  $previous_db = db_set_active('chado');
-  db_query(
+  chado_query(
     "UPDATE {stock} SET is_obsolete='t' WHERE stock_id=%d",
     $form_state['values']['make_obsolete_stock_id']
   );
-  db_set_active($previous_db);
 
 }