Project

General

Profile

Paste
Download (18.5 KB) Statistics
| Branch: | Revision:

root / drupal7 / includes / database / mysql / schema.inc @ b0dc3a2e

1
<?php
2

    
3
/**
4
 * @file
5
 * Database schema code for MySQL database servers.
6
 */
7

    
8

    
9
/**
10
 * @addtogroup schemaapi
11
 * @{
12
 */
13

    
14
class DatabaseSchema_mysql extends DatabaseSchema {
15

    
16
  /**
17
   * Maximum length of a table comment in MySQL.
18
   */
19
  const COMMENT_MAX_TABLE = 60;
20

    
21
  /**
22
   * Maximum length of a column comment in MySQL.
23
   */
24
  const COMMENT_MAX_COLUMN = 255;
25

    
26
  /**
27
   * Get information about the table and database name from the prefix.
28
   *
29
   * @return
30
   *   A keyed array with information about the database, table name and prefix.
31
   */
32
  protected function getPrefixInfo($table = 'default', $add_prefix = TRUE) {
33
    $info = array('prefix' => $this->connection->tablePrefix($table));
34
    if ($add_prefix) {
35
      $table = $info['prefix'] . $table;
36
    }
37
    if (($pos = strpos($table, '.')) !== FALSE) {
38
      $info['database'] = substr($table, 0, $pos);
39
      $info['table'] = substr($table, ++$pos);
40
    }
41
    else {
42
      $db_info = $this->connection->getConnectionOptions();
43
      $info['database'] = $db_info['database'];
44
      $info['table'] = $table;
45
    }
46
    return $info;
47
  }
48

    
49
  /**
50
   * Build a condition to match a table name against a standard information_schema.
51
   *
52
   * MySQL uses databases like schemas rather than catalogs so when we build
53
   * a condition to query the information_schema.tables, we set the default
54
   * database as the schema unless specified otherwise, and exclude table_catalog
55
   * from the condition criteria.
56
   */
57
  protected function buildTableNameCondition($table_name, $operator = '=', $add_prefix = TRUE) {
58
    $info = $this->connection->getConnectionOptions();
59

    
60
    $table_info = $this->getPrefixInfo($table_name, $add_prefix);
61

    
62
    $condition = new DatabaseCondition('AND');
63
    $condition->condition('table_schema', $table_info['database']);
64
    $condition->condition('table_name', $table_info['table'], $operator);
65
    return $condition;
66
  }
67

    
68
  /**
69
   * Generate SQL to create a new table from a Drupal schema definition.
70
   *
71
   * @param $name
72
   *   The name of the table to create.
73
   * @param $table
74
   *   A Schema API table definition array.
75
   * @return
76
   *   An array of SQL statements to create the table.
77
   */
78
  protected function createTableSql($name, $table) {
79
    $info = $this->connection->getConnectionOptions();
80

    
81
    // Provide defaults if needed.
82
    $table += array(
83
      'mysql_engine' => 'InnoDB',
84
      // Allow the default charset to be overridden in settings.php.
85
      'mysql_character_set' => $this->connection->utf8mb4IsActive() ? 'utf8mb4' : 'utf8',
86
    );
87

    
88
    $sql = "CREATE TABLE {" . $name . "} (\n";
89

    
90
    // Add the SQL statement for each field.
91
    foreach ($table['fields'] as $field_name => $field) {
92
      $sql .= $this->createFieldSql($field_name, $this->processField($field)) . ", \n";
93
    }
94

    
95
    // Process keys & indexes.
96
    $keys = $this->createKeysSql($table);
97
    if (count($keys)) {
98
      $sql .= implode(", \n", $keys) . ", \n";
99
    }
100

    
101
    // Remove the last comma and space.
102
    $sql = substr($sql, 0, -3) . "\n) ";
103

    
104
    $sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'];
105
    // By default, MySQL uses the default collation for new tables, which is
106
    // 'utf8_general_ci' for utf8. If an alternate collation has been set, it
107
    // needs to be explicitly specified.
108
    // @see DatabaseConnection_mysql
109
    if (!empty($info['collation'])) {
110
      $sql .= ' COLLATE ' . $info['collation'];
111
    }
112

    
113
    // The row format needs to be either DYNAMIC or COMPRESSED in order to allow
114
    // for the innodb_large_prefix setting to take effect, see
115
    // https://dev.mysql.com/doc/refman/5.6/en/create-table.html
116
    if ($this->connection->utf8mb4IsActive()) {
117
      $sql .= ' ROW_FORMAT=DYNAMIC';
118
    }
119

    
120
    // Add table comment.
121
    if (!empty($table['description'])) {
122
      $sql .= ' COMMENT ' . $this->prepareComment($table['description'], self::COMMENT_MAX_TABLE);
123
    }
124

    
125
    return array($sql);
126
  }
127

    
128
  /**
129
   * Create an SQL string for a field to be used in table creation or alteration.
130
   *
131
   * Before passing a field out of a schema definition into this function it has
132
   * to be processed by _db_process_field().
133
   *
134
   * @param $name
135
   *   Name of the field.
136
   * @param $spec
137
   *   The field specification, as per the schema data structure format.
138
   */
139
  protected function createFieldSql($name, $spec) {
140
    $sql = "`" . $name . "` " . $spec['mysql_type'];
141

    
142
    if (in_array($spec['mysql_type'], array('VARCHAR', 'CHAR', 'TINYTEXT', 'MEDIUMTEXT', 'LONGTEXT', 'TEXT'))) {
143
      if (isset($spec['length'])) {
144
        $sql .= '(' . $spec['length'] . ')';
145
      }
146
      if (!empty($spec['binary'])) {
147
        $sql .= ' BINARY';
148
      }
149
    }
150
    elseif (isset($spec['precision']) && isset($spec['scale'])) {
151
      $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
152
    }
153

    
154
    if (!empty($spec['unsigned'])) {
155
      $sql .= ' unsigned';
156
    }
157

    
158
    if (isset($spec['not null'])) {
159
      if ($spec['not null']) {
160
        $sql .= ' NOT NULL';
161
      }
162
      else {
163
        $sql .= ' NULL';
164
      }
165
    }
166

    
167
    if (!empty($spec['auto_increment'])) {
168
      $sql .= ' auto_increment';
169
    }
170

    
171
    // $spec['default'] can be NULL, so we explicitly check for the key here.
172
    if (array_key_exists('default', $spec)) {
173
      if (is_string($spec['default'])) {
174
        $spec['default'] = "'" . $spec['default'] . "'";
175
      }
176
      elseif (!isset($spec['default'])) {
177
        $spec['default'] = 'NULL';
178
      }
179
      $sql .= ' DEFAULT ' . $spec['default'];
180
    }
181

    
182
    if (empty($spec['not null']) && !isset($spec['default'])) {
183
      $sql .= ' DEFAULT NULL';
184
    }
185

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

    
191
    return $sql;
192
  }
193

    
194
  /**
195
   * Set database-engine specific properties for a field.
196
   *
197
   * @param $field
198
   *   A field description array, as specified in the schema documentation.
199
   */
200
  protected function processField($field) {
201

    
202
    if (!isset($field['size'])) {
203
      $field['size'] = 'normal';
204
    }
205

    
206
    // Set the correct database-engine specific datatype.
207
    // In case one is already provided, force it to uppercase.
208
    if (isset($field['mysql_type'])) {
209
      $field['mysql_type'] = drupal_strtoupper($field['mysql_type']);
210
    }
211
    else {
212
      $map = $this->getFieldTypeMap();
213
      $field['mysql_type'] = $map[$field['type'] . ':' . $field['size']];
214
    }
215

    
216
    if (isset($field['type']) && $field['type'] == 'serial') {
217
      $field['auto_increment'] = TRUE;
218
    }
219

    
220
    return $field;
221
  }
222

    
223
  public function getFieldTypeMap() {
224
    // Put :normal last so it gets preserved by array_flip. This makes
225
    // it much easier for modules (such as schema.module) to map
226
    // database types back into schema types.
227
    // $map does not use drupal_static as its value never changes.
228
    static $map = array(
229
      'varchar:normal'  => 'VARCHAR',
230
      'char:normal'     => 'CHAR',
231

    
232
      'text:tiny'       => 'TINYTEXT',
233
      'text:small'      => 'TINYTEXT',
234
      'text:medium'     => 'MEDIUMTEXT',
235
      'text:big'        => 'LONGTEXT',
236
      'text:normal'     => 'TEXT',
237

    
238
      'serial:tiny'     => 'TINYINT',
239
      'serial:small'    => 'SMALLINT',
240
      'serial:medium'   => 'MEDIUMINT',
241
      'serial:big'      => 'BIGINT',
242
      'serial:normal'   => 'INT',
243

    
244
      'int:tiny'        => 'TINYINT',
245
      'int:small'       => 'SMALLINT',
246
      'int:medium'      => 'MEDIUMINT',
247
      'int:big'         => 'BIGINT',
248
      'int:normal'      => 'INT',
249

    
250
      'float:tiny'      => 'FLOAT',
251
      'float:small'     => 'FLOAT',
252
      'float:medium'    => 'FLOAT',
253
      'float:big'       => 'DOUBLE',
254
      'float:normal'    => 'FLOAT',
255

    
256
      'numeric:normal'  => 'DECIMAL',
257

    
258
      'blob:big'        => 'LONGBLOB',
259
      'blob:normal'     => 'BLOB',
260
    );
261
    return $map;
262
  }
263

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

    
267
    if (!empty($spec['primary key'])) {
268
      $keys[] = 'PRIMARY KEY (' . $this->createKeysSqlHelper($spec['primary key']) . ')';
269
    }
270
    if (!empty($spec['unique keys'])) {
271
      foreach ($spec['unique keys'] as $key => $fields) {
272
        $keys[] = 'UNIQUE KEY `' . $key . '` (' . $this->createKeysSqlHelper($fields) . ')';
273
      }
274
    }
275
    if (!empty($spec['indexes'])) {
276
      foreach ($spec['indexes'] as $index => $fields) {
277
        $keys[] = 'INDEX `' . $index . '` (' . $this->createKeysSqlHelper($fields) . ')';
278
      }
279
    }
280

    
281
    return $keys;
282
  }
283

    
284
  protected function createKeySql($fields) {
285
    $return = array();
286
    foreach ($fields as $field) {
287
      if (is_array($field)) {
288
        $return[] = '`' . $field[0] . '`(' . $field[1] . ')';
289
      }
290
      else {
291
        $return[] = '`' . $field . '`';
292
      }
293
    }
294
    return implode(', ', $return);
295
  }
296

    
297
  protected function createKeysSqlHelper($fields) {
298
    $return = array();
299
    foreach ($fields as $field) {
300
      if (is_array($field)) {
301
        $return[] = '`' . $field[0] . '`(' . $field[1] . ')';
302
      }
303
      else {
304
        $return[] = '`' . $field . '`';
305
      }
306
    }
307
    return implode(', ', $return);
308
  }
309

    
310
  public function renameTable($table, $new_name) {
311
    if (!$this->tableExists($table)) {
312
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename @table to @table_new: table @table doesn't exist.", array('@table' => $table, '@table_new' => $new_name)));
313
    }
314
    if ($this->tableExists($new_name)) {
315
      throw new DatabaseSchemaObjectExistsException(t("Cannot rename @table to @table_new: table @table_new already exists.", array('@table' => $table, '@table_new' => $new_name)));
316
    }
317

    
318
    $info = $this->getPrefixInfo($new_name);
319
    return $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO `' . $info['table'] . '`');
320
  }
321

    
322
  public function dropTable($table) {
323
    if (!$this->tableExists($table)) {
324
      return FALSE;
325
    }
326

    
327
    $this->connection->query('DROP TABLE {' . $table . '}');
328
    return TRUE;
329
  }
330

    
331
  public function addField($table, $field, $spec, $keys_new = array()) {
332
    if (!$this->tableExists($table)) {
333
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add field @table.@field: table doesn't exist.", array('@field' => $field, '@table' => $table)));
334
    }
335
    if ($this->fieldExists($table, $field)) {
336
      throw new DatabaseSchemaObjectExistsException(t("Cannot add field @table.@field: field already exists.", array('@field' => $field, '@table' => $table)));
337
    }
338

    
339
    $fixnull = FALSE;
340
    if (!empty($spec['not null']) && !isset($spec['default'])) {
341
      $fixnull = TRUE;
342
      $spec['not null'] = FALSE;
343
    }
344
    $query = 'ALTER TABLE {' . $table . '} ADD ';
345
    $query .= $this->createFieldSql($field, $this->processField($spec));
346
    if ($keys_sql = $this->createKeysSql($keys_new)) {
347
      $query .= ', ADD ' . implode(', ADD ', $keys_sql);
348
    }
349
    $this->connection->query($query);
350
    if (isset($spec['initial'])) {
351
      $this->connection->update($table)
352
        ->fields(array($field => $spec['initial']))
353
        ->execute();
354
    }
355
    if ($fixnull) {
356
      $spec['not null'] = TRUE;
357
      $this->changeField($table, $field, $field, $spec);
358
    }
359
  }
360

    
361
  public function dropField($table, $field) {
362
    if (!$this->fieldExists($table, $field)) {
363
      return FALSE;
364
    }
365

    
366
    $this->connection->query('ALTER TABLE {' . $table . '} DROP `' . $field . '`');
367
    return TRUE;
368
  }
369

    
370
  public function fieldSetDefault($table, $field, $default) {
371
    if (!$this->fieldExists($table, $field)) {
372
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
373
    }
374

    
375
    if (!isset($default)) {
376
      $default = 'NULL';
377
    }
378
    else {
379
      $default = is_string($default) ? "'$default'" : $default;
380
    }
381

    
382
    $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` SET DEFAULT ' . $default);
383
  }
384

    
385
  public function fieldSetNoDefault($table, $field) {
386
    if (!$this->fieldExists($table, $field)) {
387
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
388
    }
389

    
390
    $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` DROP DEFAULT');
391
  }
392

    
393
  public function indexExists($table, $name) {
394
    // Returns one row for each column in the index. Result is string or FALSE.
395
    // Details at http://dev.mysql.com/doc/refman/5.0/en/show-index.html
396
    $row = $this->connection->query('SHOW INDEX FROM {' . $table . "} WHERE key_name = '$name'")->fetchAssoc();
397
    return isset($row['Key_name']);
398
  }
399

    
400
  public function addPrimaryKey($table, $fields) {
401
    if (!$this->tableExists($table)) {
402
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", array('@table' => $table)));
403
    }
404
    if ($this->indexExists($table, 'PRIMARY')) {
405
      throw new DatabaseSchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", array('@table' => $table)));
406
    }
407

    
408
    $this->connection->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . $this->createKeySql($fields) . ')');
409
  }
410

    
411
  public function dropPrimaryKey($table) {
412
    if (!$this->indexExists($table, 'PRIMARY')) {
413
      return FALSE;
414
    }
415

    
416
    $this->connection->query('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
417
    return TRUE;
418
  }
419

    
420
  public function addUniqueKey($table, $name, $fields) {
421
    if (!$this->tableExists($table)) {
422
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
423
    }
424
    if ($this->indexExists($table, $name)) {
425
      throw new DatabaseSchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", array('@table' => $table, '@name' => $name)));
426
    }
427

    
428
    $this->connection->query('ALTER TABLE {' . $table . '} ADD UNIQUE KEY `' . $name . '` (' . $this->createKeySql($fields) . ')');
429
  }
430

    
431
  public function dropUniqueKey($table, $name) {
432
    if (!$this->indexExists($table, $name)) {
433
      return FALSE;
434
    }
435

    
436
    $this->connection->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
437
    return TRUE;
438
  }
439

    
440
  public function addIndex($table, $name, $fields) {
441
    if (!$this->tableExists($table)) {
442
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", array('@table' => $table, '@name' => $name)));
443
    }
444
    if ($this->indexExists($table, $name)) {
445
      throw new DatabaseSchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", array('@table' => $table, '@name' => $name)));
446
    }
447

    
448
    $this->connection->query('ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this->createKeySql($fields) . ')');
449
  }
450

    
451
  public function dropIndex($table, $name) {
452
    if (!$this->indexExists($table, $name)) {
453
      return FALSE;
454
    }
455

    
456
    $this->connection->query('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`');
457
    return TRUE;
458
  }
459

    
460
  public function changeField($table, $field, $field_new, $spec, $keys_new = array()) {
461
    if (!$this->fieldExists($table, $field)) {
462
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", array('@table' => $table, '@name' => $field)));
463
    }
464
    if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
465
      throw new DatabaseSchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", array('@table' => $table, '@name' => $field, '@name_new' => $field_new)));
466
    }
467

    
468
    $sql = 'ALTER TABLE {' . $table . '} CHANGE `' . $field . '` ' . $this->createFieldSql($field_new, $this->processField($spec));
469
    if ($keys_sql = $this->createKeysSql($keys_new)) {
470
      $sql .= ', ADD ' . implode(', ADD ', $keys_sql);
471
    }
472
    $this->connection->query($sql);
473
  }
474

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

    
479
    // Truncate comment to maximum comment length.
480
    if (isset($length)) {
481
      // Add table prefixes before truncating.
482
      $comment = truncate_utf8($this->connection->prefixTables($comment), $length, TRUE, TRUE);
483
    }
484

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

    
488
  /**
489
   * Retrieve a table or column comment.
490
   */
491
  public function getComment($table, $column = NULL) {
492
    $condition = $this->buildTableNameCondition($table);
493
    if (isset($column)) {
494
      $condition->condition('column_name', $column);
495
      $condition->compile($this->connection, $this);
496
      // Don't use {} around information_schema.columns table.
497
      return $this->connection->query("SELECT column_comment FROM information_schema.columns WHERE " . (string) $condition, $condition->arguments())->fetchField();
498
    }
499
    $condition->compile($this->connection, $this);
500
    // Don't use {} around information_schema.tables table.
501
    $comment = $this->connection->query("SELECT table_comment FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();
502
    // Work-around for MySQL 5.0 bug http://bugs.mysql.com/bug.php?id=11379
503
    return preg_replace('/; InnoDB free:.*$/', '', $comment);
504
  }
505

    
506
  public function tableExists($table) {
507
    // The information_schema table is very slow to query under MySQL 5.0.
508
    // Instead, we try to select from the table in question.  If it fails,
509
    // the most likely reason is that it does not exist. That is dramatically
510
    // faster than using information_schema.
511
    // @link http://bugs.mysql.com/bug.php?id=19588
512
    // @todo: This override should be removed once we require a version of MySQL
513
    // that has that bug fixed.
514
    try {
515
      $this->connection->queryRange("SELECT 1 FROM {" . $table . "}", 0, 1);
516
      return TRUE;
517
    }
518
    catch (Exception $e) {
519
      return FALSE;
520
    }
521
  }
522

    
523
  public function fieldExists($table, $column) {
524
    // The information_schema table is very slow to query under MySQL 5.0.
525
    // Instead, we try to select from the table and field in question. If it
526
    // fails, the most likely reason is that it does not exist. That is
527
    // dramatically faster than using information_schema.
528
    // @link http://bugs.mysql.com/bug.php?id=19588
529
    // @todo: This override should be removed once we require a version of MySQL
530
    // that has that bug fixed.
531
    try {
532
      $this->connection->queryRange("SELECT $column FROM {" . $table . "}", 0, 1);
533
      return TRUE;
534
    }
535
    catch (Exception $e) {
536
      return FALSE;
537
    }
538
  }
539

    
540
}
541

    
542
/**
543
 * @} End of "addtogroup schemaapi".
544
 */