function chado_insert_record

2.x tripal_core.chado_query.api.inc chado_insert_record($table, $values, $options = array())
3.x tripal_chado.query.api.inc chado_insert_record($table, $values, $options = array())

Provides a generic routine for inserting into any Chado table

Use this function to insert a record into any Chado table. The first argument specifies the table for inserting and the second is an array of values to be inserted. The array is mutli-dimensional such that foreign key lookup values can be specified.

  $values =  array(
    'organism_id' => array(
        'genus' => 'Citrus',
        'species' => 'sinensis',
     ),
    'name' => 'orange1.1g000034m.g',
    'uniquename' => 'orange1.1g000034m.g',
    'type_id' => array (
        'cv_id' => array (
           'name' => 'sequence',
        ),
        'name' => 'gene',
        'is_obsolete' => 0
     ),
  );
  $result = chado_insert_record('feature',$values);

The above code inserts a record into the feature table. The $values array is nested such that the organism is selected by way of the organism_id foreign key constraint by specifying the genus and species. The cvterm is also specified using its foreign key and the cv_id for the cvterm is nested as well.

Parameters

$table: The name of the chado table for inserting

$values: An associative array containing the values for inserting.

$options: An array of options such as:

  • 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.
  • return_record: by default, the function will return the record but with the primary keys added after insertion. To simply return TRUE on success set this option to FALSE

Return value

On success this function returns the inserted record with the new primary keys added to the returned array. On failure, it returns FALSE.

Example usage:

Related topics

49 calls to chado_insert_record()
chado_analysis_insert in legacy/tripal_analysis/includes/tripal_analysis.chado_node.inc
Implements hook_insert(). When a new chado_analysis node is created we also need to add information to our chado_analysis table. This function is called on insert of a new node of type 'chado_analysis' and inserts the necessary information.
chado_associate_cvterm in tripal_chado/api/modules/tripal_chado.cv.api.inc
Add a record to a cvterm linking table (ie: feature_cvterm).
chado_associate_dbxref in tripal_chado/api/modules/tripal_chado.db.api.inc
Add a record to a database reference linking table (ie: feature_dbxref).
chado_contact_insert in legacy/tripal_contact/includes/tripal_contact.chado_node.inc
Implements of hook_insert().
chado_featuremap_insert in legacy/tripal_featuremap/includes/tripal_featuremap.chado_node.inc
Implements hook_insert().

... See full list

1 string reference to 'chado_insert_record'

File

tripal_chado/api/tripal_chado.query.api.inc, line 423
Provides an API for querying of chado including inserting, updating, deleting and selecting from chado.

Code

function chado_insert_record($table, $values, $options = array()) {

  $print_errors = (isset($options['print_errors'])) ? $options['print_errors'] : FALSE;

  if (!is_array($values)) {
    tripal_report_error('tripal_chado', TRIPAL_ERROR, 
    'Cannot pass non array as values for inserting.', array(), 
    array('print' => $print_errors)
    );
    return FALSE;
  }
  if (count($values) == 0) {
    tripal_report_error('tripal_chado', TRIPAL_ERROR, 
    'Cannot pass an empty array as values for inserting.', 
    array(), array('print' => $print_errors)
    );
    return FALSE;
  }

  // Set defaults for options. If we don't set defaults then
  // we get memory leaks when we try to access the elements.
  if (!is_array($options)) {
    $options = array();
  }

  if (!array_key_exists('skip_validation', $options)) {
    $options['skip_validation'] = FALSE;
  }
  if (!array_key_exists('return_record', $options)) {
    $options['return_record'] = TRUE;
  }

  $insert_values = array();

  if (array_key_exists('skip_validation', $options)) {
    $validate = !$options['skip_validation'];
  }
  else {
    $validate = TRUE;
  }

  // Get the table description.
  $table_desc = chado_get_schema($table);
  if (!$table_desc) {
    tripal_report_error('tripal_chado', TRIPAL_WARNING, 
    'chado_insert_record; There is no table description for !table_name', 
    array('!table_name' => $table), array('print' => $print_errors)
    );
    return;
  }

  // Iterate through the values array and create a new 'insert_values' array
  // that has all the values needed for insert with all foreign relationsihps
  // resolved.
  foreach ($values as $field => $value) {
    // Make sure the field is in the table description. If not then return an 
    // error message.
    if (!array_key_exists($field, $table_desc['fields'])) {
      tripal_report_error('tripal_chado', TRIPAL_ERROR, 
      "chado_insert_record; The field '%field' does not exist " .
        "for the table '%table'.  Cannot perform insert. Values: %array", 
      array('%field' => $field, '%table' => $table, '%array' => print_r($values, 1)), 
      array('print' => $print_errors)
      );
      return FALSE;
    }

    if (is_array($value)) {
      // Select the value from the foreign key relationship for this value.
      $results = chado_schema_get_foreign_key($table_desc, $field, $value);

      if (sizeof($results) > 1) {
        tripal_report_error('tripal_chado', TRIPAL_ERROR, 
        'chado_insert_record: Too many records match the criteria supplied for !foreign_key foreign key constraint (!criteria)', 
        array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), 
        array('print' => $print_errors)
        );
        return FALSE;
      }
      elseif (sizeof($results) < 1) {
        tripal_report_error('tripal_chado', TRIPAL_DEBUG, 
        'chado_insert_record: no record matches criteria supplied for !foreign_key foreign key constraint (!criteria)', 
        array('!foreign_key' => $field, '!criteria' => print_r($value, TRUE)), 
        array('print' => $print_errors)
        );
        return FALSE;
      }
      else {
        $insert_values[$field] = $results[0];
      }
    }
    else {
      $insert_values[$field] = $value;
    }
  }

  if ($validate) {

    // Check for violation of any unique constraints.
    $ukeys = array();
    if (array_key_exists('unique keys', $table_desc)) {
      $ukeys = $table_desc['unique keys'];
    }
    $ukselect_cols = array();
    $ukselect_vals = array();
    if ($ukeys) {
      foreach ($ukeys as $name => $fields) {
        foreach ($fields as $index => $field) {
          // Build the arrays for performing a select that will check the constraint.
          $ukselect_cols[] = $field;
          if (!array_key_exists($field, $insert_values)) {
            if (array_key_exists('default', $table_desc['fields'][$field])) {
              $ukselect_vals[$field] = $table_desc['fields'][$field]['default'];
            }
          }
          else {
            $ukselect_vals[$field] = $insert_values[$field];
          }
        }
        // Now check the constraint.
        if (chado_select_record($table, $ukselect_cols, $ukselect_vals)) {
          tripal_report_error('tripal_chado', TRIPAL_ERROR, 
          "chado_insert_record; Cannot insert duplicate record into $table table: !values", 
          array('!values' => print_r($values, TRUE)), array('print' => $print_errors)
          );
          return FALSE;
        }
      }
    }

    // If trying to insert a field that is the primary key, make sure it also
    // is unique.
    if (array_key_exists('primary key', $table_desc)) {
      $pkey = $table_desc['primary key'][0];
      if (array_key_exists($pkey, $insert_values)) {
        $coptions = array();
        if (chado_select_record($table, array($pkey), array($pkey => $insert_values[$pkey]), $coptions)) {
          tripal_report_error('tripal_chado', TRIPAL_ERROR, 
          'chado_insert_record; Cannot insert duplicate primary key into !table table: !values', 
          array('!table' => $table, '!values' => print_r($values, TRUE)), 
          array('print' => $print_errors)
          );
          return FALSE;
        }
      }
    }

    // Make sure required fields have a value.
    if (!is_array($table_desc['fields'])) {
      $table_desc['fields'] = array();
      tripal_report_error('tripal_chado', TRIPAL_WARNING, 
      "chado_insert_record; %table missing fields: \n %schema", 
      array('%table' => $table, '%schema' => print_r($table_desc, 1)), 
      array('print' => $print_errors)
      );
    }
    foreach ($table_desc['fields'] as $field => $def) {
      // A field is considered missing if it cannot be NULL and there is no
      // default value for it or it is of type 'serial'.
      if (array_key_exists('NOT NULL', $def) and 
        !array_key_exists($field, $insert_values) and 
        !array_key_exists('default', $def) and 
        strcmp($def['type'], serial) != 0) {
        tripal_report_error('tripal_chado', TRIPAL_ERROR, 
        "chado_insert_record; Field %table.%field cannot be NULL: %values", 
        array('%table' => $table, '%field' => $field, '%values' => print_r($values, 1)), 
        array('print' => $print_errors)
        );
        return FALSE;
      }
    }
  }
  // End of validation.

  // 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.
  foreach ($insert_values as $field => $value) {
    $ifields[] = $field;
    if (strcmp($value, '__NULL__') == 0) {
      $itypes[] = "NULL";
    }
    else {
      $itypes[] = ":$field";
      $ivalues[":$field"] = $value;
    }
  }

  // Create the SQL.
  $sql = 'INSERT INTO {' . $table . '} (' . implode(", ", $ifields) . ") VALUES (" . implode(", ", $itypes) . ")";
  $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 = "SELECT CURRVAL('{" . $table . "_" . $field . "_seq}')";
        $results = chado_query($sql);
        $value = $results->fetchField();
        if (!$value) {
          tripal_report_error('tripal_chado', TRIPAL_ERROR, 
          "chado_insert_record; not able to retrieve primary key after insert: %sql", 
          array('%sql' => $sql), 
          array('print' => $print_errors)
          );
          return FALSE;
        }
        $values[$field] = $value;
      }
    }
    return $values;
  }
  elseif ($options['return_record'] == FALSE and $result) {
    return TRUE;
  }
  else {
    tripal_report_error('tripal_chado', TRIPAL_ERROR, 
    'chado_insert_record; Cannot insert record into "%table": %values', 
    array('%table' => $table, '%values' => print_r($values, 1)), 
    array('print' => $print_errors)
    );
    return FALSE;
  }

  return FALSE;

}