Projet

Général

Profil

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

root / drupal7 / includes / database / mysql / database.inc @ 6ff32cea

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

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

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

    
67
    // Set MySQL init_commands if not already defined.  Default Drupal's MySQL
68
    // behavior to conform more closely to SQL standards.  This allows Drupal
69
    // to run almost seamlessly on many different kinds of database systems.
70
    // These settings force MySQL to behave the same as postgresql, or sqlite
71
    // in regards to syntax interpretation and invalid data handling.  See
72
    // http://drupal.org/node/344575 for further discussion. Also, as MySQL 5.5
73
    // changed the meaning of TRADITIONAL we need to spell out the modes one by
74
    // one.
75
    $connection_options += array(
76
      'init_commands' => array(),
77
    );
78
    $connection_options['init_commands'] += array(
79
      'sql_mode' => "SET sql_mode = 'ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
80
    );
81
    // Set connection options.
82
    $this->exec(implode('; ', $connection_options['init_commands']));
83
  }
84

    
85
  public function __destruct() {
86
    if ($this->needsCleanup) {
87
      $this->nextIdDelete();
88
    }
89
  }
90

    
91
  public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
92
    return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
93
  }
94

    
95
  public function queryTemporary($query, array $args = array(), array $options = array()) {
96
    $tablename = $this->generateTemporaryTableName();
97
    $this->query('CREATE TEMPORARY TABLE {' . $tablename . '} Engine=MEMORY ' . $query, $args, $options);
98
    return $tablename;
99
  }
100

    
101
  public function driver() {
102
    return 'mysql';
103
  }
104

    
105
  public function databaseType() {
106
    return 'mysql';
107
  }
108

    
109
  public function mapConditionOperator($operator) {
110
    // We don't want to override any of the defaults.
111
    return NULL;
112
  }
113

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

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

    
156
  /**
157
   * Overridden to work around issues to MySQL not supporting transactional DDL.
158
   */
159
  protected function popCommittableTransactions() {
160
    // Commit all the committable layers.
161
    foreach (array_reverse($this->transactionLayers) as $name => $active) {
162
      // Stop once we found an active transaction.
163
      if ($active) {
164
        break;
165
      }
166

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

    
204

    
205
/**
206
 * @} End of "addtogroup database".
207
 */