Projet

Général

Profil

Paste
Télécharger (18,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / database / mysql / schema.inc @ 01dfd3b5

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
    // Ensure the table name is not surrounded with quotes as that is not
61
    // appropriate for schema queries.
62
    $quote_char = variable_get('mysql_identifier_quote_character', MYSQL_IDENTIFIER_QUOTE_CHARACTER_DEFAULT);
63
    $table_name = str_replace($quote_char, '', $table_name);
64

    
65
    $table_info = $this->getPrefixInfo($table_name, $add_prefix);
66

    
67
    $condition = new DatabaseCondition('AND');
68
    $condition->condition('table_schema', $table_info['database']);
69
    $condition->condition('table_name', $table_info['table'], $operator);
70
    return $condition;
71
  }
72

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

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

    
93
    $sql = "CREATE TABLE {" . $name . "} (\n";
94

    
95
    // Add the SQL statement for each field.
96
    foreach ($table['fields'] as $field_name => $field) {
97
      $sql .= $this->createFieldSql($field_name, $this->processField($field)) . ", \n";
98
    }
99

    
100
    // Process keys & indexes.
101
    $keys = $this->createKeysSql($table);
102
    if (count($keys)) {
103
      $sql .= implode(", \n", $keys) . ", \n";
104
    }
105

    
106
    // Remove the last comma and space.
107
    $sql = substr($sql, 0, -3) . "\n) ";
108

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

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

    
125
    // Add table comment.
126
    if (!empty($table['description'])) {
127
      $sql .= ' COMMENT ' . $this->prepareComment($table['description'], self::COMMENT_MAX_TABLE);
128
    }
129

    
130
    return array($sql);
131
  }
132

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

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

    
159
    if (!empty($spec['unsigned'])) {
160
      $sql .= ' unsigned';
161
    }
162

    
163
    if (isset($spec['not null'])) {
164
      if ($spec['not null']) {
165
        $sql .= ' NOT NULL';
166
      }
167
      else {
168
        $sql .= ' NULL';
169
      }
170
    }
171

    
172
    if (!empty($spec['auto_increment'])) {
173
      $sql .= ' auto_increment';
174
    }
175

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

    
187
    if (empty($spec['not null']) && !isset($spec['default'])) {
188
      $sql .= ' DEFAULT NULL';
189
    }
190

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

    
196
    return $sql;
197
  }
198

    
199
  /**
200
   * Set database-engine specific properties for a field.
201
   *
202
   * @param $field
203
   *   A field description array, as specified in the schema documentation.
204
   */
205
  protected function processField($field) {
206

    
207
    if (!isset($field['size'])) {
208
      $field['size'] = 'normal';
209
    }
210

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

    
221
    if (isset($field['type']) && $field['type'] == 'serial') {
222
      $field['auto_increment'] = TRUE;
223
    }
224

    
225
    return $field;
226
  }
227

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

    
237
      'text:tiny'       => 'TINYTEXT',
238
      'text:small'      => 'TINYTEXT',
239
      'text:medium'     => 'MEDIUMTEXT',
240
      'text:big'        => 'LONGTEXT',
241
      'text:normal'     => 'TEXT',
242

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

    
249
      'int:tiny'        => 'TINYINT',
250
      'int:small'       => 'SMALLINT',
251
      'int:medium'      => 'MEDIUMINT',
252
      'int:big'         => 'BIGINT',
253
      'int:normal'      => 'INT',
254

    
255
      'float:tiny'      => 'FLOAT',
256
      'float:small'     => 'FLOAT',
257
      'float:medium'    => 'FLOAT',
258
      'float:big'       => 'DOUBLE',
259
      'float:normal'    => 'FLOAT',
260

    
261
      'numeric:normal'  => 'DECIMAL',
262

    
263
      'blob:big'        => 'LONGBLOB',
264
      'blob:normal'     => 'BLOB',
265
    );
266
    return $map;
267
  }
268

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

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

    
286
    return $keys;
287
  }
288

    
289
  protected function createKeySql($fields) {
290
    $return = array();
291
    foreach ($fields as $field) {
292
      if (is_array($field)) {
293
        $return[] = '`' . $field[0] . '`(' . $field[1] . ')';
294
      }
295
      else {
296
        $return[] = '`' . $field . '`';
297
      }
298
    }
299
    return implode(', ', $return);
300
  }
301

    
302
  protected function createKeysSqlHelper($fields) {
303
    $return = array();
304
    foreach ($fields as $field) {
305
      if (is_array($field)) {
306
        $return[] = '`' . $field[0] . '`(' . $field[1] . ')';
307
      }
308
      else {
309
        $return[] = '`' . $field . '`';
310
      }
311
    }
312
    return implode(', ', $return);
313
  }
314

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

    
323
    $info = $this->getPrefixInfo($new_name);
324
    return $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO `' . $info['table'] . '`');
325
  }
326

    
327
  public function dropTable($table) {
328
    if (!$this->tableExists($table)) {
329
      return FALSE;
330
    }
331

    
332
    $this->connection->query('DROP TABLE {' . $table . '}');
333
    return TRUE;
334
  }
335

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

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

    
366
  public function dropField($table, $field) {
367
    if (!$this->fieldExists($table, $field)) {
368
      return FALSE;
369
    }
370

    
371
    $this->connection->query('ALTER TABLE {' . $table . '} DROP `' . $field . '`');
372
    return TRUE;
373
  }
374

    
375
  public function fieldSetDefault($table, $field, $default) {
376
    if (!$this->fieldExists($table, $field)) {
377
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
378
    }
379

    
380
    if (!isset($default)) {
381
      $default = 'NULL';
382
    }
383
    else {
384
      $default = is_string($default) ? "'$default'" : $default;
385
    }
386

    
387
    $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` SET DEFAULT ' . $default);
388
  }
389

    
390
  public function fieldSetNoDefault($table, $field) {
391
    if (!$this->fieldExists($table, $field)) {
392
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", array('@table' => $table, '@field' => $field)));
393
    }
394

    
395
    $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN `' . $field . '` DROP DEFAULT');
396
  }
397

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

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

    
413
    $this->connection->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . $this->createKeySql($fields) . ')');
414
  }
415

    
416
  public function dropPrimaryKey($table) {
417
    if (!$this->indexExists($table, 'PRIMARY')) {
418
      return FALSE;
419
    }
420

    
421
    $this->connection->query('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
422
    return TRUE;
423
  }
424

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

    
433
    $this->connection->query('ALTER TABLE {' . $table . '} ADD UNIQUE KEY `' . $name . '` (' . $this->createKeySql($fields) . ')');
434
  }
435

    
436
  public function dropUniqueKey($table, $name) {
437
    if (!$this->indexExists($table, $name)) {
438
      return FALSE;
439
    }
440

    
441
    $this->connection->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
442
    return TRUE;
443
  }
444

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

    
453
    $this->connection->query('ALTER TABLE {' . $table . '} ADD INDEX `' . $name . '` (' . $this->createKeySql($fields) . ')');
454
  }
455

    
456
  public function dropIndex($table, $name) {
457
    if (!$this->indexExists($table, $name)) {
458
      return FALSE;
459
    }
460

    
461
    $this->connection->query('ALTER TABLE {' . $table . '} DROP INDEX `' . $name . '`');
462
    return TRUE;
463
  }
464

    
465
  public function changeField($table, $field, $field_new, $spec, $keys_new = array()) {
466
    if (!$this->fieldExists($table, $field)) {
467
      throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", array('@table' => $table, '@name' => $field)));
468
    }
469
    if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
470
      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)));
471
    }
472

    
473
    $sql = 'ALTER TABLE {' . $table . '} CHANGE `' . $field . '` ' . $this->createFieldSql($field_new, $this->processField($spec));
474
    if ($keys_sql = $this->createKeysSql($keys_new)) {
475
      $sql .= ', ADD ' . implode(', ADD ', $keys_sql);
476
    }
477
    $this->connection->query($sql);
478
  }
479

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

    
484
    // Truncate comment to maximum comment length.
485
    if (isset($length)) {
486
      // Add table prefixes before truncating.
487
      $comment = truncate_utf8($this->connection->prefixTables($comment), $length, TRUE, TRUE);
488
    }
489

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

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

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

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

    
545
}
546

    
547
/**
548
 * @} End of "addtogroup schemaapi".
549
 */