You are here

function db_add_column in Drupal 6

Same name and namespace in other branches
  1. 4 update.php \db_add_column()
  2. 5 update.php \db_add_column()

Add a column to a database using syntax appropriate for PostgreSQL. Save result of SQL commands in $ret array.

Note: when you add a column with NOT NULL and you are not sure if there are already rows in the table, you MUST also add DEFAULT. Otherwise PostgreSQL won't work when the table is not empty, and db_add_column() will fail. To have an empty string as the default, you must use: 'default' => "''" in the $attributes array. If NOT NULL and DEFAULT are set the PostgreSQL version will set values of the added column in old rows to the DEFAULT value.

Parameters

$ret: Array to which results will be added.

$table: Name of the table, without {}

$column: Name of the column

$type: Type of column

$attributes: Additional optional attributes. Recognized attributes: not null => TRUE|FALSE default => NULL|FALSE|value (the value must be enclosed in '' marks)

Return value

nothing, but modifies $ret parameter.

3 calls to db_add_column()
system_update_6005 in modules/system/system.install
Add language to url_alias table and modify indexes.
system_update_6011 in modules/system/system.install
Add language support to nodes
system_update_6016 in modules/system/system.install
Make {node}'s primary key be nid, change nid,vid to a unique key. Add primary keys to block, filters, flood, permission, and term_relation.

File

./update.php, line 50
Administrative page for handling updates from one Drupal version to another.

Code

function db_add_column(&$ret, $table, $column, $type, $attributes = array()) {
  if (array_key_exists('not null', $attributes) and $attributes['not null']) {
    $not_null = 'NOT NULL';
  }
  if (array_key_exists('default', $attributes)) {
    if (is_null($attributes['default'])) {
      $default_val = 'NULL';
      $default = 'default NULL';
    }
    elseif ($attributes['default'] === FALSE) {
      $default = '';
    }
    else {
      $default_val = "{$attributes['default']}";
      $default = "default {$attributes['default']}";
    }
  }
  $ret[] = update_sql("ALTER TABLE {" . $table . "} ADD {$column} {$type}");
  if (!empty($default)) {
    $ret[] = update_sql("ALTER TABLE {" . $table . "} ALTER {$column} SET {$default}");
  }
  if (!empty($not_null)) {
    if (!empty($default)) {
      $ret[] = update_sql("UPDATE {" . $table . "} SET {$column} = {$default_val}");
    }
    $ret[] = update_sql("ALTER TABLE {" . $table . "} ALTER {$column} SET NOT NULL");
  }
}