Projet

Général

Profil

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

root / drupal7 / includes / database / mysql / database.inc @ 30d5b9c5

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

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

    
62
    // Force MySQL to use the UTF-8 character set. Also set the collation, if a
63
    // certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
64
    // for UTF-8.
65
    if (!empty($connection_options['collation'])) {
66
      $this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
67
    }
68
    else {
69
      $this->exec('SET NAMES utf8');
70
    }
71

    
72
    // Set MySQL init_commands if not already defined.  Default Drupal's MySQL
73
    // behavior to conform more closely to SQL standards.  This allows Drupal
74
    // to run almost seamlessly on many different kinds of database systems.
75
    // These settings force MySQL to behave the same as postgresql, or sqlite
76
    // in regards to syntax interpretation and invalid data handling.  See
77
    // http://drupal.org/node/344575 for further discussion. Also, as MySQL 5.5
78
    // changed the meaning of TRADITIONAL we need to spell out the modes one by
79
    // one.
80
    $connection_options += array(
81
      'init_commands' => array(),
82
    );
83
    $connection_options['init_commands'] += array(
84
      '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'",
85
    );
86
    // Execute initial commands.
87
    foreach ($connection_options['init_commands'] as $sql) {
88
      $this->exec($sql);
89
    }
90
  }
91

    
92
  public function __destruct() {
93
    if ($this->needsCleanup) {
94
      $this->nextIdDelete();
95
    }
96
  }
97

    
98
  public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
99
    return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
100
  }
101

    
102
  public function queryTemporary($query, array $args = array(), array $options = array()) {
103
    $tablename = $this->generateTemporaryTableName();
104
    $this->query('CREATE TEMPORARY TABLE {' . $tablename . '} Engine=MEMORY ' . $query, $args, $options);
105
    return $tablename;
106
  }
107

    
108
  public function driver() {
109
    return 'mysql';
110
  }
111

    
112
  public function databaseType() {
113
    return 'mysql';
114
  }
115

    
116
  public function mapConditionOperator($operator) {
117
    // We don't want to override any of the defaults.
118
    return NULL;
119
  }
120

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

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

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

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

    
211

    
212
/**
213
 * @} End of "addtogroup database".
214
 */