schema.inc 11.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// $Id$

/**
 * @file
 * Database schema code for MySQL database servers.
 */


/**
 * @ingroup schemaapi
 * @{
 */

class DatabaseSchema_mysql extends DatabaseSchema {

17
18
19
20
21
22
23
24
25
26
  /**
   * Maximum length of a table comment in MySQL.
   */
  const COMMENT_MAX_TABLE = 60;

  /**
   * Maximum length of a column comment in MySQL.
   */
  const COMMENT_MAX_COLUMN = 255;

27
  /**
Dries's avatar
Dries committed
28
   * Build a condition to match a table name against a standard information_schema.
29
30
31
   *
   * MySQL uses databases like schemas rather than catalogs so when we build
   * a condition to query the information_schema.tables, we set the default
Dries's avatar
Dries committed
32
   * database as the schema unless specified otherwise, and exclude table_catalog
33
34
35
36
   * from the condition criteria.
   */
  protected function buildTableNameCondition($table_name, $operator = '=') {
    $info = Database::getConnectionInfo();
37

38
39
40
41
42
43
    if (strpos($table_name, '.')) {
      list($schema, $table_name) = explode('.', $table_name);
    }
    else {
      $schema = $info['default']['database'];
    }
44

45
46
47
    $condition = new DatabaseCondition('AND');
    $condition->condition('table_schema', $schema);
    $condition->condition('table_name', $table_name, $operator);
48
49
    return $condition;
  }
50
51
52
53
54
55
56
57
58
59
60
61

  /**
   * Generate SQL to create a new table from a Drupal schema definition.
   *
   * @param $name
   *   The name of the table to create.
   * @param $table
   *   A Schema API table definition array.
   * @return
   *   An array of SQL statements to create the table.
   */
  protected function createTableSql($name, $table) {
62
63
64
65
66
    // Provide some defaults if needed
    $table += array(
      'mysql_engine' => 'InnoDB',
      'mysql_character_set' => 'UTF8',
    );
67

68
    $sql = "CREATE TABLE {" . $name . "} (\n";
69

70
71
72
73
    // Add the SQL statement for each field.
    foreach ($table['fields'] as $field_name => $field) {
      $sql .= $this->createFieldSql($field_name, $this->processField($field)) . ", \n";
    }
74

75
76
77
78
79
    // Process keys & indexes.
    $keys = $this->createKeysSql($table);
    if (count($keys)) {
      $sql .= implode(", \n", $keys) . ", \n";
    }
80

81
82
    // Remove the last comma and space.
    $sql = substr($sql, 0, -3) . "\n) ";
83

84
    $sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'];
85

86
87
88
89
90
    // Add table comment.
    if (!empty($table['description'])) {
      $sql .= ' COMMENT ' . $this->prepareComment($table['description'], self::COMMENT_MAX_TABLE);
    }

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    return array($sql);
  }

  /**
   * 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().
   *
   * @param $name
   *   Name of the field.
   * @param $spec
   *   The field specification, as per the schema data structure format.
   */
  protected function createFieldSql($name, $spec) {
    $sql = "`" . $name . "` " . $spec['mysql_type'];
107

108
    if (in_array($spec['type'], array('varchar', 'char', 'text')) && isset($spec['length'])) {
109
110
111
112
113
      $sql .= '(' . $spec['length'] . ')';
    }
    elseif (isset($spec['precision']) && isset($spec['scale'])) {
      $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
    }
114

115
116
117
    if (!empty($spec['unsigned'])) {
      $sql .= ' unsigned';
    }
118

119
120
121
    if (!empty($spec['not null'])) {
      $sql .= ' NOT NULL';
    }
122

123
124
125
    if (!empty($spec['auto_increment'])) {
      $sql .= ' auto_increment';
    }
126

127
    // $spec['default'] can be NULL, so we explicitly check for the key here.
128
    if (array_key_exists('default', $spec)) {
129
130
131
      if (is_string($spec['default'])) {
        $spec['default'] = "'" . $spec['default'] . "'";
      }
132
133
134
      elseif (is_null($spec['default'])) {
        $spec['default'] = 'NULL';
      }
135
136
      $sql .= ' DEFAULT ' . $spec['default'];
    }
137

138
139
140
    if (empty($spec['not null']) && !isset($spec['default'])) {
      $sql .= ' DEFAULT NULL';
    }
141

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

147
148
    return $sql;
  }
149

150
151
152
153
154
155
156
  /**
   * Set database-engine specific properties for a field.
   *
   * @param $field
   *   A field description array, as specified in the schema documentation.
   */
  protected function processField($field) {
157

158
159
160
    if (!isset($field['size'])) {
      $field['size'] = 'normal';
    }
161

162
163
164
165
166
    // Set the correct database-engine specific datatype.
    if (!isset($field['mysql_type'])) {
      $map = db_type_map();
      $field['mysql_type'] = $map[$field['type'] . ':' . $field['size']];
    }
167

168
169
170
    if ($field['type'] == 'serial') {
      $field['auto_increment'] = TRUE;
    }
171

172
173
174
175
    return $field;
  }

  public function getFieldTypeMap() {
176
    // Put :normal last so it gets preserved by array_flip. This makes
177
178
    // it much easier for modules (such as schema.module) to map
    // database types back into schema types.
179
    // $map does not use drupal_static as its value never changes.
180
181
182
    static $map = array(
      'varchar:normal'  => 'VARCHAR',
      'char:normal'     => 'CHAR',
183

184
185
186
187
188
      'text:tiny'       => 'TINYTEXT',
      'text:small'      => 'TINYTEXT',
      'text:medium'     => 'MEDIUMTEXT',
      'text:big'        => 'LONGTEXT',
      'text:normal'     => 'TEXT',
189

190
191
192
193
194
      'serial:tiny'     => 'TINYINT',
      'serial:small'    => 'SMALLINT',
      'serial:medium'   => 'MEDIUMINT',
      'serial:big'      => 'BIGINT',
      'serial:normal'   => 'INT',
195

196
197
198
199
200
      'int:tiny'        => 'TINYINT',
      'int:small'       => 'SMALLINT',
      'int:medium'      => 'MEDIUMINT',
      'int:big'         => 'BIGINT',
      'int:normal'      => 'INT',
201

202
203
204
205
206
      'float:tiny'      => 'FLOAT',
      'float:small'     => 'FLOAT',
      'float:medium'    => 'FLOAT',
      'float:big'       => 'DOUBLE',
      'float:normal'    => 'FLOAT',
207

208
      'numeric:normal'  => 'DECIMAL',
209

210
211
      'blob:big'        => 'LONGBLOB',
      'blob:normal'     => 'BLOB',
212

213
214
215
216
      'datetime:normal' => 'DATETIME',
    );
    return $map;
  }
217

218
219
220
221
222
223
224
225
226
227
228



  protected function createKeysSql($spec) {
    $keys = array();

    if (!empty($spec['primary key'])) {
      $keys[] = 'PRIMARY KEY (' . $this->createKeysSqlHelper($spec['primary key']) . ')';
    }
    if (!empty($spec['unique keys'])) {
      foreach ($spec['unique keys'] as $key => $fields) {
229
        $keys[] = 'UNIQUE KEY `' . $key . '` (' . $this->createKeysSqlHelper($fields) . ')';
230
231
232
233
      }
    }
    if (!empty($spec['indexes'])) {
      foreach ($spec['indexes'] as $index => $fields) {
234
        $keys[] = 'INDEX `' . $index . '` (' . $this->createKeysSqlHelper($fields) . ')';
235
236
237
238
239
      }
    }

    return $keys;
  }
240

241
242
243
244
  protected function createKeySql($fields) {
    $ret = array();
    foreach ($fields as $field) {
      if (is_array($field)) {
245
        $ret[] = '`' . $field[0] . '`(' . $field[1] . ')';
246
247
      }
      else {
248
        $ret[] = '`' . $field . '`';
249
250
251
252
253
254
255
256
257
      }
    }
    return implode(', ', $ret);
  }

  protected function createKeysSqlHelper($fields) {
    $ret = array();
    foreach ($fields as $field) {
      if (is_array($field)) {
258
        $ret[] = '`' . $field[0] . '`(' . $field[1] . ')';
259
260
      }
      else {
261
        $ret[] = '`' . $field . '`';
262
263
264
265
266
267
268
269
      }
    }
    return implode(', ', $ret);
  }

  public function renameTable(&$ret, $table, $new_name) {
    $ret[] = update_sql('ALTER TABLE {' . $table . '} RENAME TO {' . $new_name . '}');
  }
270

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
  public function dropTable(&$ret, $table) {
    $ret[] = update_sql('DROP TABLE {' . $table . '}');
  }

  public function addField(&$ret, $table, $field, $spec, $keys_new = array()) {
    $fixnull = FALSE;
    if (!empty($spec['not null']) && !isset($spec['default'])) {
      $fixnull = TRUE;
      $spec['not null'] = FALSE;
    }
    $query = 'ALTER TABLE {' . $table . '} ADD ';
    $query .= $this->createFieldSql($field, $this->processField($spec));
    if (count($keys_new)) {
      $query .= ', ADD ' . implode(', ADD ', $this->createKeysSql($keys_new));
    }
    $ret[] = update_sql($query);
    if (isset($spec['initial'])) {
      // All this because update_sql does not support %-placeholders.
289
290
      $sql = 'UPDATE {' . $table . '} SET ' . $field . ' = :value';
      $result = db_query($sql, array(':value' => $spec['initial']));
291
292
293
294
295
296
297
298
299
      $ret[] = array('success' => $result !== FALSE, 'query' => check_plain($sql . ' (' . $spec['initial'] . ')'));
    }
    if ($fixnull) {
      $spec['not null'] = TRUE;
      $this->changeField($ret, $table, $field, $field, $spec);
    }
  }

  public function dropField(&$ret, $table, $field) {
300
    $ret[] = update_sql('ALTER TABLE {' . $table . '} DROP `' . $field . '`');
301
302
303
  }

  public function fieldSetDefault(&$ret, $table, $field, $default) {
304
    if (is_null($default)) {
305
306
307
308
309
      $default = 'NULL';
    }
    else {
      $default = is_string($default) ? "'$default'" : $default;
    }
310

311
    $ret[] = update_sql('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` SET DEFAULT ' . $default);
312
313
314
  }

  public function fieldSetNoDefault(&$ret, $table, $field) {
315
    $ret[] = update_sql('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` DROP DEFAULT');
316
317
318
319
320
  }

  public function addPrimaryKey(&$ret, $table, $fields) {
    $ret[] = update_sql('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . $this->createKeySql($fields) . ')');
  }
321

322
323
324
325
326
  public function dropPrimaryKey(&$ret, $table) {
    $ret[] = update_sql('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
  }

  public function addUniqueKey(&$ret, $table, $name, $fields) {
327
    $ret[] = update_sql('ALTER TABLE {' . $table . '} ADD UNIQUE KEY `' . $name . '` (' . $this->createKeySql($fields) . ')');
328
329
330
  }

  public function dropUniqueKey(&$ret, $table, $name) {
331
    $ret[] = update_sql('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
332
  }
333

334
  public function addIndex(&$ret, $table, $name, $fields) {
335
    $query = 'ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this->createKeySql($fields) . ')';
336
337
338
339
    $ret[] = update_sql($query);
  }

  public function dropIndex(&$ret, $table, $name) {
340
    $ret[] = update_sql('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`');
341
  }
342

343
  public function changeField(&$ret, $table, $field, $field_new, $spec, $keys_new = array()) {
344
    $sql = 'ALTER TABLE {' . $table . '} CHANGE `' . $field . '` ' . $this->createFieldSql($field_new, $this->processField($spec));
345
346
347
348
349
350
    if (count($keys_new)) {
      $sql .= ', ADD ' . implode(', ADD ', $this->createKeysSql($keys_new));
    }
    $ret[] = update_sql($sql);
  }

351
352
353
  public function prepareComment($comment, $length = NULL) {
    // Work around a bug in some versions of PDO, see http://bugs.php.net/bug.php?id=41125
    $comment = str_replace("'", '’', $comment);
354

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    // Truncate comment to maximum comment length.
    if (isset($length)) {
      // Add table prefixes before truncating.
      $comment = truncate_utf8($this->connection->prefixTables($comment), $length, TRUE, TRUE);
    }

    return $this->connection->quote($comment);
  }

  /**
   * Retrieve a table or column comment.
   */
  public function getComment($table, $column = NULL) {
    $condition = $this->buildTableNameCondition($this->connection->prefixTables('{' . $table . '}'));
    if (isset($column)) {
      $condition->condition('column_name', $column);
      $condition->compile($this->connection);
372
      // Don't use {} around information_schema.columns table.
373
374
375
      return db_query("SELECT column_comment FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
    }
    $condition->compile($this->connection);
376
    // Don't use {} around information_schema.tables table.
377
378
379
    $comment = db_query("SELECT table_comment FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
    // Work-around for MySQL 5.0 bug http://bugs.mysql.com/bug.php?id=11379
    return preg_replace('/; InnoDB free:.*$/', '', $comment);
380
381
  }

382
383
384
385
386
}

/**
 * @} End of "ingroup schemaapi".
 */