Tripal v1.0 (6.x-1.0)
Tripal Core Module

Files

file  custom_tables.php
file  views_handler_field_chado_count.inc
file  views_handler_field_dbxref_accession_link.inc
file  views_handler_field_node_optional.inc
file  views_handler_field_readable_date.inc
file  views_handler_filter_chado_boolean.inc
file  views_handler_filter_chado_select_cvterm_name.inc
file  views_handler_filter_chado_select_string.inc
file  tripal_views_handler_filter_select_cvterm.inc
file  tripal_views_handler_filter_select_string.inc

Functions

 tripal_job_set_progress ($job_id, $percentage)
 tripal_mviews_action ($op, $mview_id, $redirect=FALSE)
 tripal_core_chado_load_form ()
 tripal_core_chado_load_form_submit ($form, &$form_state)
 tripal_core_install_chado ($action)
 tripal_core_reset_chado_schema ()
 tripal_core_install_sql ($sql_file)
 tripal_core_chado_install_done ()
 tripal_custom_table_view ($table_id)
 tripal_custom_tables_list ()
 tripal_custom_tables_form (&$form_state=NULL, $table_id=NULL)
 tripal_custom_tables_form_validate ($form, &$form_state)
 tripal_custom_tables_form_submit ($form, &$form_state)
 tripal_custom_tables_action ($op, $table_id, $redirect=FALSE)
 tripal_jobs_report_form ($form, &$form_state=NULL)
 tripal_jobs_report_form_submit ($form, &$form_state=NULL)
 tripal_jobs_report ()
 tripal_jobs_view ($job_id)
 tripal_core_preprocess_tripal_core_job_view (&$variables)
 tripal_mview_report ($mview_id)
 tripal_mviews_report ()
 tripal_mviews_form (&$form_state=NULL, $mview_id=NULL)
 tripal_mviews_form_validate ($form, &$form_state)
 tripal_mviews_form_submit ($form, &$form_state)
 tripal_core_init ()
 tripal_core_menu ()
 tripal_core_perm ()
 tripal_core_theme ()
 tripal_core_job_describe_args ($callback, $args)
 print_usage ($stdout)
 runjob ($sitename, $username)

Function Documentation

print_usage ( stdout)

Print out the usage instructions if they are not followed correctly

Definition at line 52 of file tripal_launch_jobs.php.

                              {
  fwrite($stdout, "Usage:\n");
  fwrite($stdout, "  php ./sites/all/modules/tripal_core/tripal_launch_jobs <username> \n\n");
  fwrite($stdout, "    where <username> is a Drupal user name\n\n");
}
runjob ( sitename,
username 
)

Runs tripal_launch_jobs() as the specified user

Definition at line 91 of file tripal_launch_jobs_multi.php.

                                      {
  global $user;

  $_SERVER['SCRIPT_NAME'] = '/sites/all/modules/tripal_jobs/tripal_launch_jobs_multi.php';
  $_SERVER['SCRIPT_FILENAME'] = '/sites/all/modules/tripal_jobs/tripal_launch_jobs_multi.php';
  $_SERVER['HTTP_HOST'] = $sitename;
  $_SERVER['REMOTE_ADDR'] = 'localhost';
  $_SERVER['REQUEST_METHOD'] = 'GET';

  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  if (!db_fetch_object(db_query("SELECT * FROM {users} WHERE name = '%s'", $username))) {
    fwrite(STDOUT, "'$username' is not a valid Drupal username. exiting...\n");
    exit;
  }

  $user = $username;
  $user = user_load(array('name' => $username));

  tripal_jobs_launch();
}
tripal_core_chado_install_done ( )

Finish the Chado Schema Installation

Definition at line 391 of file chado_install.php.

                                          {

  // return the search path to normal
  db_query("set search_path to public");
}
tripal_core_chado_load_form ( )

Load Chado Schema Form

Definition at line 13 of file chado_install.php.

                                       {

  // we want to force the version of Chado to be set properly
  $real_version = tripal_core_set_chado_version();

  // get the effective version.  Pass true as second argument
  // to warn the user if the current version is not compatible
  $version = tripal_core_get_chado_version(FALSE, TRUE);

  $form['current_version'] = array(
    '#type' => 'item',
    '#title' => t("Current installed version of Chado"),
    '#value' => $real_version,
  );

  $form['action_to_do'] = array(
     '#type' => 'radios',
     '#title' => 'Installation/Upgrade Action',
     '#options' => array(
        'Install Chado v1.2' => t('New Install of Chado v1.2 (erases all existing Chado data if Chado already exists)'),
        'Upgrade Chado v1.11 to v1.2' => t('Upgrade existing Chado v1.11 to v1.2 (no data is lost)'),
        'Install Chado v1.11' => t('New Install of Chado v1.11 (erases all existing Chado data if Chado already exists)')
     ),
     '#description' => t('Select an action to perform'),
     '#required' => TRUE
  );

  $form['description'] = array(
    '#type' => 'item',
    '#value' => t("<font color=\"red\">WARNING:</font> A new install of Chado v1.2 or v1.11 "
      ."will install Chado within the Drupal database in a \"chado\" schema. If the \"chado\" schema already exists it will "
      ."be overwritten and all data will be lost.  You may choose to update an existing Chado v1.11 if it was installed with a previous "
      ."version of Tripal (e.g. v0.3b or v0.3.1). The update will not erase any data. "
      ."If you are using chado in a database external to the "
      ."Drupal database with a 'chado' entry in the 'settings.php' \$db_url argument "
      ."then Chado will be installed but will not be used .  The external "
      ."database specified in the settings.php file takes precedence."),
  );

  $form['button'] = array(
    '#type' => 'submit',
    '#value' => t('Install/Upgrade Chado'),
    '#weight' => 2,
  );

  return $form;
}
tripal_core_chado_load_form_submit ( form,
&$  form_state 
)

Submit Load Chado Schema 1.11 Form

Definition at line 66 of file chado_install.php.

                                                                 {
  global $user;
  $action_to_do   = trim($form_state['values']['action_to_do']);

  $args = array($action_to_do);
  tripal_add_job($action_to_do, 'tripal_core',
    'tripal_core_install_chado', $args, $user->uid);
}
tripal_core_init ( )

Implements hook_init(). Used to set the search_path, create default content and set default variables.

Definition at line 58 of file tripal_core.module.

                            {
  global $base_url;     
  
  // we need to declare here the persistent_chado global variable
  global $persistent_chado;
  global $prepared_statements;
  $persistent_chado = NULL;
  $prepared_statements = array();
  
  // add javascript files 
  drupal_add_js(drupal_get_path('theme', 'tripal') . '/js/tripal.ahah.js');
  
  // create the 'tripal' controlled volcabulary in chado but only if it doesn't already exist, and
  // only if the chado database is present.
  if (tripal_core_is_chado_installed()) {
  
    // make sure the current version of chado is set
    tripal_core_set_chado_version();  
  
    if (!db_fetch_object(chado_query("SELECT * FROM {cv} WHERE name = 'tripal'"))) {
      $results = chado_query(
        "INSERT INTO {cv} (name,definition) ".
        "VALUES ('tripal', 'Terms used by Tripal for modules to manage data such as that stored in property tables like featureprop, analysisprop, etc')");
    }
    if (!db_fetch_object(chado_query("SELECT * FROM {db} WHERE name = 'tripal'"))) {
      $results = chado_query(
        "INSERT INTO {db} (name,description) ".
        "VALUES ('tripal', 'Used as a database placeholder for tripal defined objects such as tripal cvterms')");
    }
  }

  // add some variables for all javasript to use for building URLs
  global $base_url;
  $theme_dir = drupal_get_path('theme', 'tripal');
  $clean_urls = variable_get('clean_url', 0);
  drupal_add_js(
    " var baseurl  = '$base_url';
      var themedir = '$theme_dir';
      var isClean  =  $clean_urls;",
    'inline', 'header');

  // make sure the date time settings are the way Tripal will insert them
  // otherwise PostgreSQL version that may have a different datestyle setting
  // will fail when inserting or updating a date column in a table.
  db_query("SET DATESTYLE TO '%s'", 'MDY'); 

  // in the event that an errant Tripal or extension function fails to
  // set the postgres search_path back to noraml we do it here on 
  // init of the core
  tripal_db_set_default_search_path(); 
  
  // create a persistent connection
  $connection = tripal_db_persistent_chado();
}
tripal_core_install_chado ( action)

Install Chado Schema

Definition at line 80 of file chado_install.php.

                                            {

  $vsql = "INSERT INTO chadoprop (type_id, value) VALUES  " .
          "((SELECT cvterm_id " .
          "FROM cvterm CVT " .
          " INNER JOIN cv CV on CVT.cv_id = CV.cv_id " .
          "WHERE CV.name = 'chado_properties' AND CVT.name = 'version'), " .
          "'%s') ";

  if($action == 'Install Chado v1.2'){
    $schema_file = drupal_get_path('module', 'tripal_core') . '/chado_schema/default_schema-1.2.sql';
    $init_file = drupal_get_path('module', 'tripal_core') . '/chado_schema/initialize-1.2.sql';
    if (tripal_core_reset_chado_schema()) {
      $success = tripal_core_install_sql($schema_file);
      if ($success) {
        print "Install of Chado v1.2 (Step 1 of 2) Successful!\n";
      }
      else {
        print "Installation (Step 1 of 2) Problems!  Please check output above for errors.\n";
        exit;
      }
      $success = tripal_core_install_sql($init_file);
      if ($success) {
        print "Install of Chado v1.2 (Step 2 of 2) Successful.\nInstallation Complete\n";
      }
      else {
        print "Installation (Step 2 of 2) Problems!  Please check output above for errors.\n";
        exit;
      }
      chado_query($vsql,'1.2'); # set the version
    }
    else {
      print "ERROR: cannot install chado.  Please check database permissions\n";
      exit;
    }
  }
  elseif($action == 'Upgrade Chado v1.11 to v1.2') {
    $schema_file = drupal_get_path('module', 'tripal_core') . '/chado_schema/default_schema-1.11-1.2-diff.sql';
    $init_file = drupal_get_path('module', 'tripal_core') . '/chado_schema/upgrade-1.11-1.2.sql';
    $success = tripal_core_install_sql($schema_file);
    if ($success) {
      print "Upgrade from v1.11 to v1.2 (Step 1 of 2) Successful!\n";
    }
    else {
      print "Upgrade (Step 1 of 2) problems!  Please check output above for errors.\n";
      exit;
    }
    $success = tripal_core_install_sql($init_file);
    if ($success) {
      print "Upgrade from v1.11 to v1.2 (Step 2 of 2) Successful.\nUpgrade Complete!\n";
    }
    else {
      print "Upgrade (Step 2 of 2) problems!  Please check output above for errors.\n";
      exit;
    }
    chado_query($vsql,'1.2'); # set the version
  }
  elseif($action == 'Install Chado v1.11'){
    $schema_file = drupal_get_path('module', 'tripal_core') . '/chado_schema/default_schema-1.11.sql';
    $init_file = drupal_get_path('module', 'tripal_core') . '/chado_schema/initialize-1.11.sql';
    if (tripal_core_reset_chado_schema()) {
      $success = tripal_core_install_sql($schema_file);
      if ($success) {
        print "Install of Chado v1.11 (Step 1 of 2) Successful!\n";
      }
      else {
        print "Installation (Step 1 of 2) Problems!  Please check output above for errors.\n";
        exit;
      }
      $success = tripal_core_install_sql($init_file);
      if ($success) {
        print "Install of Chado v1.11 (Step 2 of 2) Successful.\nInstallation Complete!\n";
      }
      else {
        print "Installation (Step 2 of 2) Problems!  Please check output above for errors.\n";
        exit;
      }
    }
    else {
      print "ERROR: cannot install chado.  Please check database permissions\n";
      exit;
    }
  }
}
tripal_core_install_sql ( sql_file)

Execute the provided SQL

Parameters:
$sql_fileContains SQL statements to be executed

Definition at line 217 of file chado_install.php.

                                            {
  
  $chado_local = tripal_core_schema_exists('chado');

  if($chado_local) {
    db_query("set search_path to chado");
  }
  print "Loading $sql_file...\n";
  $lines = file($sql_file, FILE_SKIP_EMPTY_LINES);

  if (!$lines) {
    return 'Cannot open $schema_file';
  }

  $stack = array();
  $in_string = 0;
  $query = '';
  $i = 0;
  $success = 1;
  foreach ($lines as $line_num => $line) {
    $i++;
    $type = '';
    // find and remove comments except when inside of strings
    if (preg_match('/--/', $line) and !$in_string and !preg_match("/'.*?--.*?'/", $line)) {
      $line = preg_replace('/--.*$/', '', $line);  // remove comments
    }
    if (preg_match('/\/\*.*?\*\//', $line)) {
      $line = preg_replace('/\/\*.*?\*\//', '', $line);  // remove comments
    }
    // skip empty lines
    if (preg_match('/^\s*$/', $line) or strcmp($line, '')==0) {
      continue;
    }
    // Find SQL for new objects
    if (preg_match('/^\s*CREATE\s+TABLE/i', $line) and !$in_string) {
      $stack[] = 'table';
      $line = preg_replace("/public./", "chado.", $line);
    }
    if (preg_match('/^\s*ALTER\s+TABLE/i', $line) and !$in_string) {
      $stack[] = 'alter table';
      $line = preg_replace("/public./", "chado.", $line);
    }
    if (preg_match('/^\s*SET/i', $line) and !$in_string) {
      $stack[] = 'set';
    }
    if (preg_match('/^\s*CREATE\s+SCHEMA/i', $line) and !$in_string) {
      $stack[] = 'schema';
    }
    if (preg_match('/^\s*CREATE\s+SEQUENCE/i', $line) and !$in_string) {
      $stack[] = 'sequence';
      $line = preg_replace("/public./", "chado.", $line);
    }
    if (preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*VIEW/i', $line) and !$in_string) {
      $stack[] = 'view';
      $line = preg_replace("/public./", "chado.", $line);
    }
    if (preg_match('/^\s*COMMENT/i', $line) and !$in_string and sizeof($stack)==0) {
      $stack[] = 'comment';
      $line = preg_replace("/public./", "chado.", $line);
    }
    if (preg_match('/^\s*CREATE\s+(?:OR\s+REPLACE\s+)*FUNCTION/i', $line) and !$in_string) {
      $stack[] = 'function';
      $line = preg_replace("/public./", "chado.", $line);
    }
    if (preg_match('/^\s*CREATE\s+INDEX/i', $line) and !$in_string) {
      $stack[] = 'index';
    }
    if (preg_match('/^\s*INSERT\s+INTO/i', $line) and !$in_string) {
      $stack[] = 'insert';
      $line = preg_replace("/public./", "chado.", $line);
    }
    if (preg_match('/^\s*CREATE\s+TYPE/i', $line) and !$in_string) {
      $stack[] = 'type';
    }
    if (preg_match('/^\s*GRANT/i', $line) and !$in_string) {
      $stack[] = 'grant';
    }
    if (preg_match('/^\s*CREATE\s+AGGREGATE/i', $line) and !$in_string) {
      $stack[] = 'aggregate';
    }

    // determine if we are in a string that spans a line
    $matches = preg_match_all("/[']/i", $line, $temp);
    $in_string = $in_string - ($matches % 2);
    $in_string = abs($in_string);

    // if we've reached the end of an object the pop the stack
    if (strcmp($stack[sizeof($stack)-1], 'table') == 0 and preg_match('/\);\s*$/', $line)) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'alter table') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'set') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'schema') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'sequence') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'view') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'comment') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'function') == 0 and preg_match("/LANGUAGE.*?;\s+$/i", $line)) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'index') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'insert') == 0 and preg_match('/\);\s*$/', $line)) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'type') == 0 and preg_match('/\);\s*$/', $line)) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'grant') == 0 and preg_match('/;\s*$/', $line) and !$in_string) {
      $type = array_pop($stack);
    }
    if (strcmp($stack[sizeof($stack)-1], 'aggregate') == 0 and preg_match('/\);\s*$/', $line)) {
      $type = array_pop($stack);
    }
    // if we're in a recognized SQL statement then let's keep track of lines
    if ($type or sizeof($stack) > 0) {
      $query .= "$line";
    }
    else {
      print "UNHANDLED $i, $in_string: $line";
      tripal_core_chado_install_done();
      return FALSE;
    }
    if (preg_match_all("/\n/", $query, $temp) > 100) {
      print "SQL query is too long.  Terminating:\n$query\n";
      tripal_core_chado_install_done();
      return FALSE;
    }
    if ($type and sizeof($stack) == 0) {
      //print "Adding $type: line $i\n";
      // rewrite the set search_path to make 'public' be 'chado', but only if the
      // chado schema exists
      if (strcmp($type, 'set')==0 and $chado_local){
        $query = preg_replace("/public/m", "chado", $query);
      }
      
      if (!$chado_local) {
        $previous = tripal_db_set_active('chado');
      }
      $result = db_query($query);
      if (!$chado_local) {
        tripal_db_set_active($previous);
      }
      if (!$result) {
        $error  = pg_last_error();
        print "FAILED. Line  $i, $in_string\n$error:\n$query\n\n";        
        tripal_core_chado_install_done();
        $success = 0;
        return $success;
      }
      $query = '';
    }
  }
  tripal_core_chado_install_done();
  return $success;
}
tripal_core_job_describe_args ( callback,
args 
)

Implements hook_job_describe_args(). Describes the arguements for the tripal_update_mview job to allow for greater readability in the jobs details pages.

Parameters:
$callbackThe callback of the current tripal job (this is the function that will be executed when tripal_launch_jobs.php is run.
$argsAn array of arguments passed in when the job was registered.
Returns:
A more readable $args array

Definition at line 319 of file tripal_core.module.

                                                         {
  $new_args = array();
  if ($callback == 'tripal_update_mview') {
    // get this mview details
    $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
    $mview = db_fetch_object(db_query($sql, $args[0]));
    $new_args['View Name'] = $mview->name;
  }

  elseif ($callback == 'tripal_core_install_chado') {
     $new_args['Action'] = $args[0];
  }
  return $new_args;
}
tripal_core_menu ( )

Implements hook_menu(). Defines all menu items needed by Tripal Core

Definition at line 119 of file tripal_core.module.

                            {
  $items = array();

  // Triapl setting groups
  $items['admin/tripal'] = array(
    'title' => 'Tripal Management',
    'description' => "Manage the behavior or Tripal and its various modules.",
    'position' => 'right',
    'weight' => -5,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer site configuration'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
  );
  $items['admin/tripal/customize'] = array(
    'title' => 'Customize Tripal',
    'position' => 'right',
    'page callback' => 'theme',
    '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',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tripal_core_chado_load_form'),
    'access arguments' => array('install chado'),
    'type' => MENU_NORMAL_ITEM,
  );

  // Jobs Management
  $items['admin/tripal/tripal_jobs'] = array(
    'title' => 'Jobs',
    'description' => 'Jobs managed by Tripal',
    'page callback' => 'tripal_jobs_report',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/tripal/tripal_jobs/cancel/%'] = array(
    'title' => 'Jobs',
    'description' => 'Cancel a pending job',
    'page callback' => 'tripal_jobs_cancel',
    'page arguments' => array(4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/tripal/tripal_jobs/rerun/%'] = array(
    'title' => 'Jobs',
    'description' => 'Re-run an existing job.',
    'page callback' => 'tripal_jobs_rerun',
    'page arguments' => array(4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/tripal/tripal_jobs/view/%'] = array(
    'title' => 'Jobs Details',
    'description' => 'View job details.',
    'page callback' => 'tripal_jobs_view',
    'page arguments' => array(4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );

  // Materialized Views
  $items['admin/tripal/mviews'] = array(
    'title' => 'MViews',
    'description' => 'Materialized views are used to improve speed of large or complex queries.',
    'page callback' => 'tripal_mviews_report',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/tripal/mviews/report/%'] = array(
    'title' => 'Materialized View',
    'description' => 'Materialized views are used to improve speed of large or complex queries.',
    'page callback' => 'tripal_mview_report',
    'page arguments' => array(4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/tripal/mviews/new'] = array(
    'title' => 'Create MView',
    'description' => 'Materialized views are used to improve speed of large or complex queries.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tripal_mviews_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/tripal/mviews/edit/%'] = array(
    'title' => 'Edit MView',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tripal_mviews_form', 4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/tripal/mviews/action/%/%'] = array(
    'title' => 'Create MView',
    'description' => 'Materialized views are used to improve speed of large or complex queries.',
    'page callback' => 'tripal_mviews_action',
    'page arguments' => array(4, 5, "1"),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );
  
  // Custom Tables
  $items['admin/tripal/custom_tables'] = array(
    'title' => 'Custom Tables',
    'description' => 'Custom tables are added to Chado.',
    'page callback' => 'tripal_custom_tables_list',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/tripal/custom_tables/view/%'] = array(
    'title' => 'Custom Tables',
    'description' => 'Custom tables are added to Chado.',
    'page callback' => 'tripal_custom_table_view',
    'page arguments' => array(4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $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'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/tripal/custom_tables/edit/%'] = array(
    'title' => 'Edit Custom Table',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tripal_custom_tables_form', 4),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/tripal/custom_tables/action/%/%'] = array(
    'title' => 'Create Custom TAble',
    'description' => 'Custom tables are added to Chado.',
    'page callback' => 'tripal_custom_tables_action',
    'page arguments' => array(4, 5, "1"),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}
tripal_core_perm ( )

Set the permission types that the chado module uses. Essentially we want permissionis that protect creation, editing and deleting of chado data objects

Definition at line 279 of file tripal_core.module.

                            {
  return array('install chado');
}
tripal_core_preprocess_tripal_core_job_view ( &$  variables)

Registers variables for the tripal_core_job_view themeing function

Parameters:
$variablesAn array containing all variables supplied to this template

Definition at line 145 of file jobs.php.

                                                                  {

  // 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,
            TJ.end_time,TJ.priority,U.name as username,TJ.arguments,
            TJ.callback,TJ.error_msg,TJ.pid
     FROM {tripal_jobs} TJ
       INNER JOIN users U on TJ.uid = U.uid
     WHERE TJ.job_id = %d";
  $job = db_fetch_object(db_query($sql, $job_id));

  // we do not know what the arguments are for and we want to provide a
  // meaningful description to the end-user. So we use a callback function
  // deinfed in the module that created the job to describe in an array
  // the arguments provided.  If the callback fails then just use the
  // arguments as they are
  $args = preg_split("/::/", $job->arguments);
  $arg_hook = $job->modulename . "_job_describe_args";
  if (is_callable($arg_hook)) {
    $new_args = call_user_func_array($arg_hook, array($job->callback, $args));
    if (is_array($new_args) and count($new_args)) {
      $job->arguments = $new_args;
    }
    else {
      $job->arguments = $args;
    }
  }
  else {
    $job->arguments = $args;
  }

  // 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;
}
tripal_core_reset_chado_schema ( )

Reset the Chado Schema This drops the current chado and chado-related schema and re-creates it

Definition at line 171 of file chado_install.php.

                                          {
  global $active_db;

  // drop current chado and chado-related schema
  if (tripal_core_schema_exists('chado')) {
    print "Dropping existing 'chado' schema\n";
    db_query("drop schema chado cascade");
  }
  if (tripal_core_schema_exists('genetic_code')) {
    print "Dropping existing 'genetic_code' schema\n";
    db_query("drop schema genetic_code cascade");
  }
  if (tripal_core_schema_exists('so')) {
    print "Dropping existing 'so' schema\n";
    db_query("drop schema so cascade");
  }
  if (tripal_core_schema_exists('frange')) {
    print "Dropping existing 'frange' schema\n";
    db_query("drop schema frange cascade");
  }

  // create the new chado schema
  print "Creating 'chado' schema\n";
  db_query("create schema chado");
  if (tripal_core_schema_exists('chado')) {
    // before creating the plpgsql language let's check to make sure
    // it doesn't already exists
    $sql = "SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql'";
    $count = db_fetch_object(db_query($sql));
    if (!$count or $count->count == 0) {
      db_query("create language plpgsql");
    }
    return TRUE;
  }

  return FALSE;
}
tripal_core_theme ( )

Implements hook_theme(). Registers template files/functions used by this module.

Definition at line 289 of file tripal_core.module.

                             {
  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',
      'path' => drupal_get_path('module', 'tripal_core') . '/theme'
    ),
  );
}
tripal_custom_table_view ( table_id)

A template function which returns markup to display details for the custom table

Parameters:
$table_idThe unique ID of the custom table

Definition at line 19 of file custom_tables.php.

                                             {

  // get this custom_table details
  $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = %d";
  $custom_table = db_fetch_object(db_query($sql, $table_id));

  // create a table with each row containig stats for
  // an individual job in the results set.
  $return_url = url("admin/tripal/custom_tables/");
  $output .= "<p><a href=\"$return_url\">" . t("Return to list of custom tables") . "</a></p>";
  $output .= "<br />";
  $output .= "<p>Details for <b>$custom_table->table_name</b>:</p>";
  $output .= "<br />";
  $output .= "<table class=\"border-table\">";
  if ($custom_table->table_name) {
    $output .= "  <tr>".
    "    <th>Table Name</th>".
    "    <td>$custom_table->table_name</td>".
    "  </tr>";
  }
  if ($custom_table->schema) {
    $output .= "  <tr>".
    "    <th>Table Field Definitions</th>".
    "    <td><pre>" . var_export(unserialize($custom_table->schema),1) . "</pre></td>".
    "  </tr>";
  }

  // build the URLs using the url function so we can handle installations where
  // clean URLs are or are not used
  $delete_url = url("admin/tripal/custom_tables/action/delete/$custom_table->table_id");
  $edit_url = url("admin/tripal/custom_tables/edit/$custom_table->table_id");
  $output .= "<tr><th>Actions</th>".
            "<td>".
            "     <a href='$edit_url'>Edit</a>, ".
            "     <a href='$delete_url'>Delete</a></td></tr>";
  $output .= "</table>";

  return $output;
}
tripal_custom_tables_action ( op,
table_id,
redirect = FALSE 
)

Does the specified action for the specified custom table

Parameters:
$opThe action to be taken. Currenly only delete is available
$table_idThe unique ID of the custom table for the action to be performed on
$redirectTRUE/FALSE depending on whether you want to redirect the user to admin/tripal/custom_tables

Definition at line 349 of file custom_tables.php.

                                                                        {
  global $user;

  $args = array("$table_id");
  if (!$table_id) {
    return '';
  }

  // get this table details
  $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = %d";
  $custom_table = db_fetch_object(db_query($sql, $table_id));

  if ($op == 'delete') {
  
    // remove the entry from the tripal_custom tables table
    $sql = "DELETE FROM {tripal_custom_tables} ".
           "WHERE table_id = $table_id";
    db_query($sql);
    
    // drop the table from chado if it exists
    if (db_table_exists($custom_table->table_name)) {
      $success = chado_query("DROP TABLE %s", $custom_table->table_name);
      if($success){
        drupal_set_message(t("Custom Table '%name' dropped", array('%name' => $custom_table->table_name)));
      }
    }
  }

  // Redirect the user
  if ($redirect) {
    drupal_goto("admin/tripal/custom_tables");
  }
}
tripal_custom_tables_form ( &$  form_state = NULL,
table_id = NULL 
)

A Form to Create/Edit a Custom table

Parameters:
$form_stateThe current state of the form (Form API)
$table_idThe unique ID of the Custom table to Edit or NULL if creating a new table
Returns:
A form array (Form API)

Definition at line 104 of file custom_tables.php.

                                                                          {

  if (!$table_id) {
    $action = 'Add';
  }
  else {
    $action = 'Edit';
  }

  // get this requested table
  if (strcmp($action, 'Edit')==0) {
    $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = %d ";
    $custom_table = db_fetch_object(db_query($sql, $table_id));

    // 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_schema = $form_state['values']['schema'];
    $default_force_drop = $form_state['values']['force_drop'];

    if (!$default_table_name) {
      $default_table = $custom_table->table_name;
    }
    if (!$default_schema) {
      $default_schema = var_export(unserialize($custom_table->schema),1);
      $default_schema = preg_replace('/=>\s+\n\s+array/','=> array', $default_schema);
    }
  }

  // Build the form
  $form['action'] = array(
    '#type' => 'value',
    '#value' => $action
  );

  $form['table_id'] = array(
    '#type' => 'value',
    '#value' => $table_id
  );
  
  $form['instructions']= array(
    '#type'          => 'markup',
    '#value'         => 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
       a custom table. For example a table to link stocks and libraries (e.g. library_stock) would be
       a good custom table. Try to model linker or propery tables after existing tables.  If the
       table already exists it will not be modified.  To force dropping and recreation of the table
       click the checkbox below.
    '),
  );

  $form['force_drop']= array(
    '#type'          => 'checkbox',
    '#title'         => t('Re-create table'),
    '#description'   => t('Check this box if your table already exists and you would like to drop it and recreate it.'),
    '#default_value' => $default_force_drop,
  );
  $form['schema']= array(
    '#type'          => 'textarea',
    '#title'         => t('Schema Array'),
    '#description'   => t('Please enter the Drupal Schema API compatible array that defines the table.'),
    '#required'      => FALSE,
    '#default_value' => $default_schema,
    '#rows'          => 25,
  );

  if ($action == 'Edit') {
    $value = 'Save';
  }
  if ($action == 'Add') {
    $value = 'Add';
  }
  $form['submit'] = array(
    '#type'         => 'submit',
    '#value'        => t($value),
    '#executes_submit_callback' => TRUE,
  );
  $form['#redirect'] = 'admin/tripal/custom_tables';
  
  $form['example']= array(
    '#type'          => 'markup',
    '#value'         => "<br>Example library_stock table: <pre>
array (
  'table' => 'library_stock',
  'fields' => array (
    'library_stock_id' => array(
      'type' => serial,
      'not null' => TRUE,
    ),
    'library_id' => array(
      'type' => 'int',
      'not null' => TRUE,
    ),      
    'stock_id' => array(
      'type' => 'int',
      'not null' => TRUE,
    ),
  ),
  'primary key' => array(
    'library_stock_id'
  ),
  'unique keys' => array(
    'library_stock_c1' => array(
      'library_id',
      'stock_id'
    ),
  ),
  'foreign keys' => array(
    'library' => array(
      'table' => 'library',
      'columns' => array(
        'library_id' => 'library_id',
      ),
    ),
    'stock' => array(
      'table' => 'stock',
      'columns' => array(
        'stock_id' => 'stock_id',
      ),
    ),
  ),
)
    </pre>",
  );
  

  return $form;
}
tripal_custom_tables_form_submit ( form,
&$  form_state 
)

Submit the Create/Edit Custom table form Implements hook_form_submit().

Definition at line 307 of file custom_tables.php.

                                                               {

  $ret = array();
  $action = $form_state['values']['action'];
  $table_id = $form_state['values']['table_id'];
  $schema = $form_state['values']['schema'];
  $force_drop = $form_state['values']['force_drop'];
  
  $skip_creation = 1;
  if ($force_drop) {
     $skip_creation = 0;
  }

  // conver the schema into a PHP array
  $schema_arr = array();
  eval("\$schema_arr = $schema;");
  

  if (strcmp($action, 'Edit') == 0) {   
    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);
  }
  else {
    drupal_set_message(t("No action performed."));
  }

  return '';
}
tripal_custom_tables_form_validate ( form,
&$  form_state 
)

Validate the Create/Edit custom table form Implements hook_form_validate().

Definition at line 241 of file custom_tables.php.

                                                                 {
  $action = $form_state['values']['action'];
  $table_id = $form_state['values']['table_id'];
  $schema = $form_state['values']['schema'];
  $force_drop = $form_state['values']['force_drop'];

  if (!$schema) {
    form_set_error($form_state['values']['schema'],
      t('Schema array field is required.'));
  }

  // make sure the array is valid
  $schema_array = array();
  if ($schema) {
    $success = preg_match('/^\s*array/', $schema);
    if (!$success) {
      form_set_error($form_state['values']['schema'],
        t("The schema array should begin with the word 'array'."));
    }
    else {
      $success = eval("\$schema_array = $schema;");    
      if ($success === FALSE) {
        $error = error_get_last();
        form_set_error($form_state['values']['schema'],
          t("The schema array is improperly formatted. Parse Error : " . $error["message"]));
      }
      if (is_array($schema_array) and !array_key_exists('table', $schema_array)) {
        form_set_error($form_state['values']['schema'],
          t("The schema array must have key named 'table'"));
      }
      // check to see if the table name matches an existing table
      // if this is an add
      if ($action == 'Add') {
        $previous_db = tripal_db_set_active('chado');
        $exists = db_table_exists($schema_array['table']);
        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."));  
        }
      } 
      if ($action == 'Edit') {
        // see if the table name has changed. If so, then check to make sure
        // it doesn't already exists. We don't want to drop a table we didn't mean to
        $sql = "SELECT * FROM {tripal_custom_tables} WHERE table_id = %d";
        $ct = db_fetch_object(db_query($sql, $table_id));
        if ($ct->table_name != $schema_array['table']) {
          $previous_db = tripal_db_set_active('chado');
          $exists = db_table_exists($schema_array['table']);
          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."));  
          }
        }
      }     
    }
  }
}
tripal_custom_tables_list ( )

A template function to render a listing of all Custom tables

Definition at line 64 of file custom_tables.php.

                                     {
  $header = array('', 'Table Name', 'Description');
  $rows = array();
  $custom_tables = db_query("SELECT * FROM {tripal_custom_tables} ORDER BY table_name");

  while ($custom_table = db_fetch_object($custom_tables)) {
 
    $rows[] = array(
      l(t('View'), "admin/tripal/custom_tables/view/$custom_table->table_id") ." | ".
      l(t('Edit'), "admin/tripal/custom_tables/edit/$custom_table->table_id") ." | ".
      $custom_table->table_name,
      $custom_table->comment,
      l(t('Delete'), "admin/tripal/custom_tables/action/delete/$custom_table->table_id"),
    );
  }

  $rows[] = array(
    'data' => array(
      array('data' => l(t('Create a new custom table.'), "admin/tripal/custom_tables/new"),
        'colspan' => 6),
    )
  );

  $page = theme('table', $header, $rows);
  return $page;
}
tripal_job_set_progress ( job_id,
percentage 
)

An internal function for setting the progress for a current job

Parameters:
$job_idThe job_id to set the progress for
$percentageThe progress to set the job to
Returns:
True on success and False otherwise

Definition at line 315 of file tripal_core_jobs.api.inc.

                                                       {

  if (preg_match("/^(\d+|100)$/", $percentage)) {
    $record = new stdClass();
    $record->job_id = $job_id;
    $record->progress = $percentage;
    if (drupal_write_record('tripal_jobs', $record, 'job_id')) {
      return TRUE;
    }
  }

  return FALSE;
}
tripal_jobs_report ( )

Returns the Tripal Job Report

Returns:
The HTML to be rendered which describes the job report

Definition at line 59 of file jobs.php.

                              {

  // run the following function which will
  // change the status of jobs that have errored out
  tripal_jobs_check_running();

        $jobs_status_filter = $_SESSION['tripal_job_status_filter'];

  $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,
      TJ.end_time,TJ.priority,U.name as username
    FROM {tripal_jobs} TJ
      INNER JOIN {users} U on TJ.uid = U.uid ";
  if ($jobs_status_filter) {
    $sql .= "WHERE TJ.status = '%s' ";
  }
  $sql .= "ORDER BY job_id DESC";

  $jobs = pager_query($sql, 25, 0, "SELECT count(*) FROM ($sql) as t1", $jobs_status_filter);
  $header = array(
    'Job ID',
    'User',
    'Job Name',
    array('data' => 'Dates', 'style'=> "white-space: nowrap"),
    'Priority',
    'Progress',
    'Status',
    'Action');
  $rows = array();

  // iterate through the jobs
  while ($job = db_fetch_object($jobs)) {
    $submit = tripal_jobs_get_submit_date($job);
    $start = tripal_jobs_get_start_time($job);
    $end = tripal_jobs_get_end_time($job);
    $cancel_link = '';
    if ($job->start_time == 0 and $job->end_time == 0) {
      $cancel_link = "<a href=\"" . url("admin/tripal/tripal_jobs/cancel/" . $job->job_id) . "\">Cancel</a><br />";
    }
    $rerun_link = "<a href=\"" . url("admin/tripal/tripal_jobs/rerun/" . $job->job_id) . "\">Re-run</a><br />";
    $view_link ="<a href=\"" . url("admin/tripal/tripal_jobs/view/" . $job->job_id) . "\">View</a>";
    $rows[] = array(
      $job->job_id,
      $job->username,
      $job->job_name,
      "Submit Date: $submit<br>Start Time: $start<br>End Time: $end",
      $job->priority,
      $job->progress . '%',
      $job->job_status,
      "$cancel_link $rerun_link $view_link",
    );
  }

  // create the report page
  $output .= "Waiting jobs are executed first by priority level (the lower the ".
             "number the higher the priority) and second by the order they ".
             "were entered";
  $output .= drupal_get_form('tripal_jobs_report_form');
  $output .= theme('table', $header, $rows);
  $output .= theme_pager();
  return $output;
}
tripal_jobs_report_form ( form,
&$  form_state = NULL 
)

Definition at line 13 of file jobs.php.

                                                             {
  $form = array();

  // set the default values
  $default_status = $form_state['values']['job_status'];

  if (!$default_status) {
    $default_status = $_SESSION['tripal_job_status_filter'];
  }

  $form['job_status'] = array(
    '#type'          => 'select',
    '#title'         => t('Filter by Job Status'),
    '#default_value' => $default_status,
    '#options' => array(
            0           => 'All Jobs',
            'Running'   => 'Running',
            'Waiting'   => 'Waiting',
            'Completed' => 'Completed',
            'Cancelled' => 'Cancelled',
            'Error'     => 'Error',
          ),
  );

  $form['submit'] = array(
    '#type'         => 'submit',
    '#value'        => t('Filter'),
  );
  return $form;
}
tripal_jobs_report_form_submit ( form,
&$  form_state = NULL 
)

Definition at line 47 of file jobs.php.

                                                                    {
  $job_status = $form_state['values']['job_status'];
  $_SESSION['tripal_job_status_filter'] = $job_status;
}
tripal_jobs_view ( job_id)

Returns the HTML code to display a given job

Parameters:
$job_idThe job_id of the job to display
Returns:
The HTML describing the indicated job

Definition at line 133 of file jobs.php.

                                   {
  return theme('tripal_core_job_view', $job_id);
}
tripal_mview_report ( mview_id)

A template function which returns markup to display details for the current materialized view

Parameters:
$mview_idThe unique ID of the materialized view to render

Definition at line 17 of file mviews.php.

                                        {

  // get this mview details
  $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d";
  $mview = db_fetch_object(db_query($sql, $mview_id));
  
  $rows = array();

  // 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>Details for <b>$mview->name</b>:</p>";
  
  // build the URLs using the url function so we can handle installations where
  // clean URLs are or are not used
  $update_url = url("admin/tripal/mviews/action/update/$mview->mview_id");
  $delete_url = url("admin/tripal/mviews/action/delete/$mview->mview_id");
  $edit_url = url("admin/tripal/mviews/edit/$mview->mview_id");
  $rows[] = array('Actions', "<a href='$update_url'>Populate</a>, <a href='$edit_url'>Edit</a>,  <a href='$delete_url'>Delete</a>");
  
  if ($mview->last_update > 0) {    
    $update = format_date($mview->last_update);
  }
  else {
    $update = 'Not yet populated';
  }
  $rows[] = array('Last Update', $update);  
  if ($mview->name) {
    $rows[] = array('View Name', $mview->name);
  }
  if ($mview->modulename) {
    $rows[] = array('Module Name', $mview->modulename);    
  }
  if ($mview->mv_table) {
    $rows[] = array('Table Name', $mview->mv_table);
  }
  if ($mview->mv_specs) {
    $rows[] = array('Table Field Definitions', $mview->mv_specs);
  }
  if ($mview->query) {
    $rows[] = array('Query', "<pre>" . $mview->query . "</pre>");
  }
  if ($mview->indexed) {
    $rows[] = array('Indexed Fields', $mview->indexed);
  }
  if ($mview->special_index) {
    $rows[] = array('Special Indexed Fields', $mview->special_index);
  }
  if ($mview->mv_schema) {
    $rows[] = array('Drupal Schema API Definition', "<pre>" . $mview->mv_schema . "</pre>");
  }
  
  $table = theme_table(array(), $rows);
  $output .= $table;

  return $output;
}
tripal_mviews_action ( op,
mview_id,
redirect = FALSE 
)

Does the specified action for the specified Materialized View

Parameters:
$opThe action to be taken. One of update or delete
$mview_idThe unique ID of the materialized view for the action to be performed on
$redirectTRUE/FALSE depending on whether you want to redirect the user to admin/tripal/mviews

Definition at line 297 of file tripal_core_mviews.api.inc.

                                                                 {
  global $user;

  $args = array("$mview_id");
  if (!$mview_id) {
    return '';
  }

  // get this mview details
  $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d";
  $mview = db_fetch_object(db_query($sql, $mview_id));

  // add a job or perform the action based on the given operation
  if ($op == 'update') {
    tripal_add_job("Populate materialized view '$mview->name'", 'tripal_core',
       'tripal_update_mview', $args, $user->uid);
  }
  if ($op == 'delete') {
    // remove the mview from the tripal_mviews table
    $sql = "DELETE FROM {tripal_mviews} ".
           "WHERE mview_id = $mview_id";
    db_query($sql);
    // drop the table from chado if it exists
    $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);
    }
    tripal_db_set_active($previous_db);  // now use drupal database
  }

  // Redirect the user
  if ($redirect) {
    drupal_goto("admin/tripal/mviews");
  }
}
tripal_mviews_form ( &$  form_state = NULL,
mview_id = NULL 
)

A Form to Create/Edit a Materialized View

Parameters:
$form_stateThe current state of the form (Form API)
$mview_idThe unique ID of the Materialized View to Edit or NULL if creating a new materialized view
Returns:
A form array (Form API)

$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, );

Definition at line 142 of file mviews.php.

                                                                   {

  if (!$mview_id) {
    $action = 'Add';
  }
  else {
    $action = 'Edit';
  }

  // set defaults for collapsed fieldsets
  $schema_collapsed = 0;
  $traditional_collapsed = 1;  
  
  
  // get this requested view
  if (strcmp($action, 'Edit')==0) {
    $sql = "SELECT * FROM {tripal_mviews} WHERE mview_id = %d ";
    $mview = db_fetch_object(db_query($sql, $mview_id));

    // 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 (!$default_name) {
      $default_name = $mview->name;
    }
    if (!$default_mv_table) {
      $default_mv_table = $mview->mv_table;
    }
    if (!$default_mv_specs) {
      $default_mv_specs = $mview->mv_specs;
    }
    if (!$default_indexed) {
      $default_indexed = $mview->indexed;
    }
    if (!$default_mvquery) {
      $default_mvquery = $mview->query;
    }
    if (!$default_special_index) {
      $default_special_index = $mview->special_index;
    }
    if (!$default_comment) {
      $default_comment = $mview->comment;
    }
    if (!$default_schema) {
      $default_schema = $mview->mv_schema;
    }
    if (!$default_modulename) {      
      $default_modulename = $mview->modulename ? $mview->modulename : 'tripal_core';
    }
    

    // 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,
    // we do not want this to show up as the mv_table is needed for the
    // traditional style input.  We'll blank it out if we have a custom
    // table and it will get reset in the submit function using the
    // 'table' value from the schema array
    if ($default_schema) {
      $default_mv_table = '';
    }
    // set which fieldset is collapsed
    if (!$default_schema) {
      $schema_collapsed = 1;
      $traditional_collapsed = 0;
    }
  }

  // Build the form
  $form['action'] = array(
    '#type' => 'value',
    '#value' => $action
  );

  $form['mview_id'] = array(
    '#type' => 'value',
    '#value' => $mview_id
  );
  
  $form['modulename'] = array(
    '#type' => 'value',
    '#value' => $default_modulename,
  );

  $form['name']= array(
    '#type'          => 'textfield',
    '#title'         => t('View Name'),
    '#description'   => t('Please enter the name for this materialized view.'),
    '#required'      => TRUE,
    '#default_value' => $default_name,
  );

  $form['comment']= array(
    '#type'          => 'textarea',
    '#title'         => t('MView Description'),
    '#description'   => t('Optional.  Please provide a description of the purpose for this materialized vieww.'),
    '#required'      => FALSE,
    '#default_value' => $default_comment,
  );

  // add a fieldset for the Drupal Schema API
  $form['schema'] = array(
    '#type' => 'fieldset',
    '#title' => 'Drupal Schema API Setup',
    '#description' => t('Use the Drupal Schema API array to describe a table. The benefit is that it '.
                       'can be fully integrated with Tripal Views.  Tripal supports an extended '.
                       'array format to allow for descriptoin of foreign key relationships.'),
    '#collapsible' => 1,
    '#collapsed' => $schema_collapsed ,
  );

  $form['schema']['schema']= array(
    '#type'          => 'textarea',
    '#title'         => t('Schema Array'),
    '#description'   => t('Please enter the Drupal Schema API compatible array that defines the table.'),
    '#required'      => FALSE,
    '#default_value' => $default_schema,
    '#rows'          => 25,
  );

  // 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['mvquery']= array(
    '#type'          => 'textarea',
    '#title'         => t('Query'),
    '#description'   => t('Please enter the SQL statement used to populate the table.'),
    '#required'      => TRUE,
    '#default_value' => $default_mvquery,
    '#rows'          => 25,
  );

  if ($action == 'Edit') {
    $value = 'Save';
  }
  if ($action == 'Add') {
    $value = 'Add';
  }
  $form['submit'] = array(
    '#type'         => 'submit',
    '#value'        => t($value),
    '#weight'       => 9,
    '#executes_submit_callback' => TRUE,
  );
  $form['#redirect'] = 'admin/tripal/mviews';

  return $form;
}
tripal_mviews_form_submit ( form,
&$  form_state 
)

Submit the Create/Edit Materialized View Form Implements hook_form_submit().

Definition at line 399 of file mviews.php.

                                                        {

  $ret = array();
  $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'];
  $query = $form_state['values']['mvquery'];
  $special_index = $form_state['values']['special_index'];
  $comment = $form_state['values']['comment'];
  $schema = $form_state['values']['schema'];
  $modulename = $form_state['values']['modulename'];

  if (strcmp($action, 'Edit') == 0) {
    tripal_edit_mview($mview_id, $name, $modulename, $mv_table, $mv_specs,
      $indexed, $query, $special_index, $comment, $schema);
  }
  elseif (strcmp($action, 'Add') == 0) {
    tripal_add_mview($name, $modulename, $mv_table, $mv_specs,
      $indexed, $query, $special_index, $comment, $schema);
  }
  else {
    drupal_set_message(t("No action performed."));
  }

  return '';
}
tripal_mviews_form_validate ( form,
&$  form_state 
)

Validate the Create/Edit Materialized View Form Implements hook_form_validate().

Definition at line 348 of file mviews.php.

                                                          {
  $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'];
  $query = $form_state['values']['mvquery'];
  $special_index = $form_state['values']['special_index'];
  $comment = $form_state['values']['comment'];
  $schema = $form_state['values']['schema'];

  if ($schema and ($mv_table or $mv_specs or $indexed or $special_index)) {
    form_set_error($form_state['values']['schema'],
      t('You can create an MView using the Drupal Schema API method or the '.
        'traditional method but not both.'));
  }
  if (!$schema) {
    if (!$mv_specs) {
      form_set_error($form_state['values']['mv_specs'],
        t('The Table Definition field is required.'));
    }
    if (!$mv_table) {
      form_set_error($form_state['values']['mv_table'],
        t('The Table Name field is required.'));
    }
  }

  // make sure the array is valid
  if ($schema) {
    $success = eval("\$schema_array = $schema;");
    if ($success === FALSE) {
      $error = error_get_last();
      form_set_error($form_state['values']['schema'],
        t("The schema array is improperly formatted. Parse Error : " . $error["message"]));
    }
    if (!array_key_exists('table', $schema_array)) {
      form_set_error($form_state['values']['schema'],
        t("The schema array must have key named 'table'"));
    }

    // TODO: add in more validation checks of the array to help the user
  }
}
tripal_mviews_report ( )

A template function to render a listing of all Materialized Views

Definition at line 81 of file mviews.php.

                                {
  $header = array('', 'MView Name', 'Last Update', 'Status', 'Description', '');
  $rows = array();
  $mviews = db_query("SELECT * FROM {tripal_mviews} ORDER BY name");

  while ($mview = db_fetch_object($mviews)) {
    if ($mview->last_update > 0) {
      $update = format_date($mview->last_update);
    }
    else {
      $update = 'Not yet populated';
    }

    $rows[] = array(
      l(t('View'), "admin/tripal/mviews/report/$mview->mview_id") ." | ".
      l(t('Edit'), "admin/tripal/mviews/edit/$mview->mview_id") ." | ".
      l(t('Populate'), "admin/tripal/mviews/action/update/$mview->mview_id"),
      $mview->name,
      $update,
      $mview->status,
      $mview->comment,
      l(t('Delete'), "admin/tripal/mviews/action/delete/$mview->mview_id"),
    );
  }

  $rows[] = array(
    'data' => array(
      array('data' => l(t('Create a new materialized view.'), "admin/tripal/mviews/new"),
        'colspan' => 6),
    )
  );
  $page = '</p>' . t("Materialized Views (MViews) are custom tables populated with a defined SQL statement.  
    Because Chado is highly normalized and highly constrained it serves as a wonderful 
    data storage platform, but unfortunately some queries may be slow.  MViews alleviate slowness by aggregating data
    into tables that are more easy to query.  Use MViews to create tables for custom search pages or custom Tripal
    module development.") . '</p>';
  $page .= '<p><b>' . t("MViews behaves in the following way:") . '</b><ul>'.
           '<li>' . t("The SQL statement defined for an MVIEW will be used to populate the table") . '</li>' .
           '<li>' . t("Altering the table structure of an MView will cause the MView table to be dropped and recreated.  All records in the MView will be lost.") . '</li>' .
           '<li>' . t("Altering the query of an existing view will not change the MView table. No records will be lost. ") . '</li>' .
           '<li>' . t("Repopulating an MView that is already populated will result in replacement of all records.") . '</li>' .
           '<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);
  return $page;
}
 All Classes Files Functions Variables