You are here

protected function DatabaseSchema_mysql::createFieldSql in Drupal 7

Create an SQL string for a field to be used in table creation or alteration.

Before passing a field out of a schema definition into this function it has to be processed by _db_process_field().

Parameters

$name: Name of the field.

$spec: The field specification, as per the schema data structure format.

3 calls to DatabaseSchema_mysql::createFieldSql()
DatabaseSchema_mysql::addField in includes/database/mysql/schema.inc
Add a new field to a table.
DatabaseSchema_mysql::changeField in includes/database/mysql/schema.inc
Change a field definition.
DatabaseSchema_mysql::createTableSql in includes/database/mysql/schema.inc
Generate SQL to create a new table from a Drupal schema definition.

File

includes/database/mysql/schema.inc, line 144
Database schema code for MySQL database servers.

Class

DatabaseSchema_mysql

Code

protected function createFieldSql($name, $spec) {
  $sql = "`" . $name . "` " . $spec['mysql_type'];
  if (in_array($spec['mysql_type'], array(
    'VARCHAR',
    'CHAR',
    'TINYTEXT',
    'MEDIUMTEXT',
    'LONGTEXT',
    'TEXT',
  ))) {
    if (isset($spec['length'])) {
      $sql .= '(' . $spec['length'] . ')';
    }
    if (!empty($spec['binary'])) {
      $sql .= ' BINARY';
    }
  }
  elseif (isset($spec['precision']) && isset($spec['scale'])) {
    $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
  }
  if (!empty($spec['unsigned'])) {
    $sql .= ' unsigned';
  }
  if (isset($spec['not null'])) {
    if ($spec['not null']) {
      $sql .= ' NOT NULL';
    }
    else {
      $sql .= ' NULL';
    }
  }
  if (!empty($spec['auto_increment'])) {
    $sql .= ' auto_increment';
  }

  // $spec['default'] can be NULL, so we explicitly check for the key here.
  if (array_key_exists('default', $spec)) {
    if (is_string($spec['default'])) {
      $spec['default'] = "'" . $spec['default'] . "'";
    }
    elseif (!isset($spec['default'])) {
      $spec['default'] = 'NULL';
    }
    $sql .= ' DEFAULT ' . $spec['default'];
  }
  if (empty($spec['not null']) && !isset($spec['default'])) {
    $sql .= ' DEFAULT NULL';
  }

  // Add column comment.
  if (!empty($spec['description'])) {
    $sql .= ' COMMENT ' . $this
      ->prepareComment($spec['description'], self::COMMENT_MAX_COLUMN);
  }
  return $sql;
}