You are here

function schema_mysql_create_table_sql in Schema 6

Same name and namespace in other branches
  1. 5 engines/schema_mysql.inc \schema_mysql_create_table_sql()
1 call to schema_mysql_create_table_sql()
schema_mysqli_create_table_sql in engines/schema_mysqli.inc

File

engines/schema_mysql.inc, line 16

Code

function schema_mysql_create_table_sql($table) {
  $sql_cols = array();
  foreach ($table['fields'] as $colname => $col) {
    $sql = $colname . ' ' . schema_engine_type($col, 'mysql');
    if (isset($col['unsigned']) && $col['unsigned']) {
      $sql .= ' UNSIGNED';
    }
    unset($col['unsigned']);
    if (isset($col['length']) && $col['length']) {
      $sql .= '(' . $col['length'] . ')';
    }
    if (isset($col['type']) && $col['type'] == 'serial') {
      $sql .= ' AUTO_INCREMENT';
    }
    unset($col['type']);
    unset($col['length']);
    if (isset($col['not null']) && $col['not null']) {
      $sql .= ' NOT NULL';
    }
    unset($col['not null']);
    foreach ($col as $prop => $val) {
      switch ($prop) {
        case 'default':
          $sql .= " {$prop} ";
          if (is_string($val)) {
            $sql .= "'{$val}'";
          }
          else {
            $sql .= $val;
          }
          break;
      }
    }
    $sql_cols[] = $sql;
  }
  $sql_keys = array();
  if (is_array($table['primary key'])) {
    $sql_keys[] = 'PRIMARY KEY (' . implode(', ', $table['primary key']) . ')';
  }
  foreach (array(
    'unique keys',
    'indexes',
  ) as $type) {
    if (isset($table[$type]) && is_array($table[$type])) {
      foreach ($table[$type] as $keyname => $key) {
        $sql = '';
        if ($type == 'unique keys') {
          $sql = 'UNIQUE ';
        }
        $sql .= 'KEY ' . $keyname . ' ';
        $sql .= '(' . implode(', ', $key) . ')';
        $sql_keys[] = $sql;
      }
    }
  }
  $sql = "CREATE TABLE {" . $table['name'] . "} (\n\t";
  $sql .= implode(",\n\t", $sql_cols);
  if (count($sql_keys) > 0) {
    $sql .= ",\n\t";
  }
  $sql .= implode(",\n\t", $sql_keys);
  $sql .= "\n";
  $sql .= ") /*!40100 DEFAULT CHARACTER SET utf8 */;\n\n";
  return $sql;
}