Projet

Général

Profil

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

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

1
<?php
2

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

    
8
/**
9
 * @addtogroup database
10
 * @{
11
 */
12

    
13
class DatabaseConnection_mysql extends DatabaseConnection {
14

    
15
  /**
16
   * Flag to indicate if the cleanup function in __destruct() should run.
17
   *
18
   * @var boolean
19
   */
20
  protected $needsCleanup = FALSE;
21

    
22
  public function __construct(array $connection_options = array()) {
23
    // This driver defaults to transaction support, except if explicitly passed FALSE.
24
    $this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
25

    
26
    // MySQL never supports transactional DDL.
27
    $this->transactionalDDLSupport = FALSE;
28

    
29
    $this->connectionOptions = $connection_options;
30

    
31
    $charset = 'utf8';
32
    // Check if the charset is overridden to utf8mb4 in settings.php.
33
    if ($this->utf8mb4IsActive()) {
34
      $charset = 'utf8mb4';
35
    }
36

    
37
    // The DSN should use either a socket or a host/port.
38
    if (isset($connection_options['unix_socket'])) {
39
      $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
40
    }
41
    else {
42
      // Default to TCP connection on port 3306.
43
      $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
44
    }
45
    // Character set is added to dsn to ensure PDO uses the proper character
46
    // set when escaping. This has security implications. See
47
    // https://www.drupal.org/node/1201452 for further discussion.
48
    $dsn .= ';charset=' . $charset;
49
    $dsn .= ';dbname=' . $connection_options['database'];
50
    // Allow PDO options to be overridden.
51
    $connection_options += array(
52
      'pdo' => array(),
53
    );
54
    $connection_options['pdo'] += array(
55
      // So we don't have to mess around with cursors and unbuffered queries by default.
56
      PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
57
      // Because MySQL's prepared statements skip the query cache, because it's dumb.
58
      PDO::ATTR_EMULATE_PREPARES => TRUE,
59
    );
60
    if (defined('PDO::MYSQL_ATTR_MULTI_STATEMENTS')) {
61
      // An added connection option in PHP 5.5.21+ to optionally limit SQL to a
62
      // single statement like mysqli.
63
      $connection_options['pdo'] += array(PDO::MYSQL_ATTR_MULTI_STATEMENTS => FALSE);
64
    }
65

    
66
    parent::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
67

    
68
    // Force MySQL to use the UTF-8 character set. Also set the collation, if a
69
    // certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
70
    // for UTF-8.
71
    if (!empty($connection_options['collation'])) {
72
      $this->exec('SET NAMES ' . $charset . ' COLLATE ' . $connection_options['collation']);
73
    }
74
    else {
75
      $this->exec('SET NAMES ' . $charset);
76
    }
77

    
78
    // Set MySQL init_commands if not already defined.  Default Drupal's MySQL
79
    // behavior to conform more closely to SQL standards.  This allows Drupal
80
    // to run almost seamlessly on many different kinds of database systems.
81
    // These settings force MySQL to behave the same as postgresql, or sqlite
82
    // in regards to syntax interpretation and invalid data handling.  See
83
    // http://drupal.org/node/344575 for further discussion. Also, as MySQL 5.5
84
    // changed the meaning of TRADITIONAL we need to spell out the modes one by
85
    // one.
86
    $connection_options += array(
87
      'init_commands' => array(),
88
    );
89
    $connection_options['init_commands'] += array(
90
      'sql_mode' => "SET sql_mode = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
91
    );
92
    // Execute initial commands.
93
    foreach ($connection_options['init_commands'] as $sql) {
94
      $this->exec($sql);
95
    }
96
  }
97

    
98
  public function __destruct() {
99
    if ($this->needsCleanup) {
100
      $this->nextIdDelete();
101
    }
102
  }
103

    
104
  public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
105
    return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
106
  }
107

    
108
  public function queryTemporary($query, array $args = array(), array $options = array()) {
109
    $tablename = $this->generateTemporaryTableName();
110
    $this->query('CREATE TEMPORARY TABLE {' . $tablename . '} Engine=MEMORY ' . $query, $args, $options);
111
    return $tablename;
112
  }
113

    
114
  public function driver() {
115
    return 'mysql';
116
  }
117

    
118
  public function databaseType() {
119
    return 'mysql';
120
  }
121

    
122
  public function mapConditionOperator($operator) {
123
    // We don't want to override any of the defaults.
124
    return NULL;
125
  }
126

    
127
  public function nextId($existing_id = 0) {
128
    $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
129
    // This should only happen after an import or similar event.
130
    if ($existing_id >= $new_id) {
131
      // If we INSERT a value manually into the sequences table, on the next
132
      // INSERT, MySQL will generate a larger value. However, there is no way
133
      // of knowing whether this value already exists in the table. MySQL
134
      // provides an INSERT IGNORE which would work, but that can mask problems
135
      // other than duplicate keys. Instead, we use INSERT ... ON DUPLICATE KEY
136
      // UPDATE in such a way that the UPDATE does not do anything. This way,
137
      // duplicate keys do not generate errors but everything else does.
138
      $this->query('INSERT INTO {sequences} (value) VALUES (:value) ON DUPLICATE KEY UPDATE value = value', array(':value' => $existing_id));
139
      $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array('return' => Database::RETURN_INSERT_ID));
140
    }
141
    $this->needsCleanup = TRUE;
142
    return $new_id;
143
  }
144

    
145
  public function nextIdDelete() {
146
    // While we want to clean up the table to keep it up from occupying too
147
    // much storage and memory, we must keep the highest value in the table
148
    // because InnoDB  uses an in-memory auto-increment counter as long as the
149
    // server runs. When the server is stopped and restarted, InnoDB
150
    // reinitializes the counter for each table for the first INSERT to the
151
    // table based solely on values from the table so deleting all values would
152
    // be a problem in this case. Also, TRUNCATE resets the auto increment
153
    // counter.
154
    try {
155
      $max_id = $this->query('SELECT MAX(value) FROM {sequences}')->fetchField();
156
      // We know we are using MySQL here, no need for the slower db_delete().
157
      $this->query('DELETE FROM {sequences} WHERE value < :value', array(':value' => $max_id));
158
    }
159
    // During testing, this function is called from shutdown with the
160
    // simpletest prefix stored in $this->connection, and those tables are gone
161
    // by the time shutdown is called so we need to ignore the database
162
    // errors. There is no problem with completely ignoring errors here: if
163
    // these queries fail, the sequence will work just fine, just use a bit
164
    // more database storage and memory.
165
    catch (PDOException $e) {
166
    }
167
  }
168

    
169
  /**
170
   * Overridden to work around issues to MySQL not supporting transactional DDL.
171
   */
172
  protected function popCommittableTransactions() {
173
    // Commit all the committable layers.
174
    foreach (array_reverse($this->transactionLayers) as $name => $active) {
175
      // Stop once we found an active transaction.
176
      if ($active) {
177
        break;
178
      }
179

    
180
      // If there are no more layers left then we should commit.
181
      unset($this->transactionLayers[$name]);
182
      if (empty($this->transactionLayers)) {
183
        if (!PDO::commit()) {
184
          throw new DatabaseTransactionCommitFailedException();
185
        }
186
      }
187
      else {
188
        // Attempt to release this savepoint in the standard way.
189
        try {
190
          $this->query('RELEASE SAVEPOINT ' . $name);
191
        }
192
        catch (PDOException $e) {
193
          // However, in MySQL (InnoDB), savepoints are automatically committed
194
          // when tables are altered or created (DDL transactions are not
195
          // supported). This can cause exceptions due to trying to release
196
          // savepoints which no longer exist.
197
          //
198
          // To avoid exceptions when no actual error has occurred, we silently
199
          // succeed for MySQL error code 1305 ("SAVEPOINT does not exist").
200
          if ($e->errorInfo[1] == '1305') {
201
            // If one SAVEPOINT was released automatically, then all were.
202
            // Therefore, clean the transaction stack.
203
            $this->transactionLayers = array();
204
            // We also have to explain to PDO that the transaction stack has
205
            // been cleaned-up.
206
            PDO::commit();
207
          }
208
          else {
209
            throw $e;
210
          }
211
        }
212
      }
213
    }
214
  }
215

    
216
  public function utf8mb4IsConfigurable() {
217
    return TRUE;
218
  }
219

    
220
  public function utf8mb4IsActive() {
221
    return isset($this->connectionOptions['charset']) && $this->connectionOptions['charset'] === 'utf8mb4';
222
  }
223

    
224
  public function utf8mb4IsSupported() {
225
    // Ensure that the MySQL driver supports utf8mb4 encoding.
226
    $version = $this->getAttribute(PDO::ATTR_CLIENT_VERSION);
227
    if (strpos($version, 'mysqlnd') !== FALSE) {
228
      // The mysqlnd driver supports utf8mb4 starting at version 5.0.9.
229
      $version = preg_replace('/^\D+([\d.]+).*/', '$1', $version);
230
      if (version_compare($version, '5.0.9', '<')) {
231
        return FALSE;
232
      }
233
    }
234
    else {
235
      // The libmysqlclient driver supports utf8mb4 starting at version 5.5.3.
236
      if (version_compare($version, '5.5.3', '<')) {
237
        return FALSE;
238
      }
239
    }
240

    
241
    // Ensure that the MySQL server supports large prefixes and utf8mb4.
242
    try {
243
      $this->query("CREATE TABLE {drupal_utf8mb4_test} (id VARCHAR(255), PRIMARY KEY(id(255))) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci ROW_FORMAT=DYNAMIC ENGINE=INNODB");
244
    }
245
    catch (Exception $e) {
246
      return FALSE;
247
    }
248
    $this->query("DROP TABLE {drupal_utf8mb4_test}");
249
    return TRUE;
250
  }
251
}
252

    
253

    
254
/**
255
 * @} End of "addtogroup database".
256
 */