Projet

Général

Profil

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

root / drupal7 / includes / database / sqlite / database.inc @ 01dfd3b5

1
<?php
2

    
3
/**
4
 * @file
5
 * Database interface code for SQLite embedded database engine.
6
 */
7

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

    
13
include_once DRUPAL_ROOT . '/includes/database/prefetch.inc';
14

    
15
/**
16
 * Specific SQLite implementation of DatabaseConnection.
17
 */
18
class DatabaseConnection_sqlite extends DatabaseConnection {
19

    
20
  /**
21
   * Whether this database connection supports savepoints.
22
   *
23
   * Version of sqlite lower then 3.6.8 can't use savepoints.
24
   * See http://www.sqlite.org/releaselog/3_6_8.html
25
   *
26
   * @var boolean
27
   */
28
  protected $savepointSupport = FALSE;
29

    
30
  /**
31
   * Whether or not the active transaction (if any) will be rolled back.
32
   *
33
   * @var boolean
34
   */
35
  protected $willRollback;
36

    
37
  /**
38
   * All databases attached to the current database. This is used to allow
39
   * prefixes to be safely handled without locking the table
40
   *
41
   * @var array
42
   */
43
  protected $attachedDatabases = array();
44

    
45
  /**
46
   * Whether or not a table has been dropped this request: the destructor will
47
   * only try to get rid of unnecessary databases if there is potential of them
48
   * being empty.
49
   *
50
   * This variable is set to public because DatabaseSchema_sqlite needs to
51
   * access it. However, it should not be manually set.
52
   *
53
   * @var boolean
54
   */
55
  var $tableDropped = FALSE;
56

    
57
  public function __construct(array $connection_options = array()) {
58
    // We don't need a specific PDOStatement class here, we simulate it below.
59
    $this->statementClass = NULL;
60

    
61
    // This driver defaults to transaction support, except if explicitly passed FALSE.
62
    $this->transactionSupport = $this->transactionalDDLSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE;
63

    
64
    $this->connectionOptions = $connection_options;
65

    
66
    // Allow PDO options to be overridden.
67
    $connection_options += array(
68
      'pdo' => array(),
69
    );
70
    $connection_options['pdo'] += array(
71
      // Convert numeric values to strings when fetching.
72
      PDO::ATTR_STRINGIFY_FETCHES => TRUE,
73
    );
74
    parent::__construct('sqlite:' . $connection_options['database'], '', '', $connection_options['pdo']);
75

    
76
    // Attach one database for each registered prefix.
77
    $prefixes = $this->prefixes;
78
    foreach ($prefixes as $table => &$prefix) {
79
      // Empty prefix means query the main database -- no need to attach anything.
80
      if (!empty($prefix)) {
81
        // Only attach the database once.
82
        if (!isset($this->attachedDatabases[$prefix])) {
83
          $this->attachedDatabases[$prefix] = $prefix;
84
          $this->query('ATTACH DATABASE :database AS :prefix', array(':database' => $connection_options['database'] . '-' . $prefix, ':prefix' => $prefix));
85
        }
86

    
87
        // Add a ., so queries become prefix.table, which is proper syntax for
88
        // querying an attached database.
89
        $prefix .= '.';
90
      }
91
    }
92
    // Regenerate the prefixes replacement table.
93
    $this->setPrefix($prefixes);
94

    
95
    // Detect support for SAVEPOINT.
96
    $version = $this->query('SELECT sqlite_version()')->fetchField();
97
    $this->savepointSupport = (version_compare($version, '3.6.8') >= 0);
98

    
99
    // Create functions needed by SQLite.
100
    $this->sqliteCreateFunction('if', array($this, 'sqlFunctionIf'));
101
    $this->sqliteCreateFunction('greatest', array($this, 'sqlFunctionGreatest'));
102
    $this->sqliteCreateFunction('pow', 'pow', 2);
103
    $this->sqliteCreateFunction('length', 'strlen', 1);
104
    $this->sqliteCreateFunction('md5', 'md5', 1);
105
    $this->sqliteCreateFunction('concat', array($this, 'sqlFunctionConcat'));
106
    $this->sqliteCreateFunction('substring', array($this, 'sqlFunctionSubstring'), 3);
107
    $this->sqliteCreateFunction('substring_index', array($this, 'sqlFunctionSubstringIndex'), 3);
108
    $this->sqliteCreateFunction('rand', array($this, 'sqlFunctionRand'));
109

    
110
    // Enable the Write-Ahead Logging (WAL) option for SQLite if supported.
111
    // @see https://www.drupal.org/node/2348137
112
    // @see https://sqlite.org/wal.html
113
    if (version_compare($version, '3.7') >= 0) {
114
      $connection_options += array(
115
        'init_commands' => array(),
116
      );
117
      $connection_options['init_commands'] += array(
118
        'wal' => "PRAGMA journal_mode=WAL",
119
      );
120
    }
121

    
122
    // Execute sqlite init_commands.
123
    if (isset($connection_options['init_commands'])) {
124
      $this->exec(implode('; ', $connection_options['init_commands']));
125
    }
126
  }
127

    
128
  /**
129
   * Destructor for the SQLite connection.
130
   *
131
   * We prune empty databases on destruct, but only if tables have been
132
   * dropped. This is especially needed when running the test suite, which
133
   * creates and destroy databases several times in a row.
134
   */
135
  public function __destruct() {
136
    if ($this->tableDropped && !empty($this->attachedDatabases)) {
137
      foreach ($this->attachedDatabases as $prefix) {
138
        // Check if the database is now empty, ignore the internal SQLite tables.
139
        try {
140
          $count = $this->query('SELECT COUNT(*) FROM ' . $prefix . '.sqlite_master WHERE type = :type AND name NOT LIKE :pattern', array(':type' => 'table', ':pattern' => 'sqlite_%'))->fetchField();
141

    
142
          // We can prune the database file if it doesn't have any tables.
143
          if ($count == 0 && $this->connectionOptions['database'] != ':memory:') {
144
            // Detaching the database fails at this point, but no other queries
145
            // are executed after the connection is destructed so we can simply
146
            // remove the database file.
147
            unlink($this->connectionOptions['database'] . '-' . $prefix);
148
          }
149
        }
150
        catch (Exception $e) {
151
          // Ignore the exception and continue. There is nothing we can do here
152
          // to report the error or fail safe.
153
        }
154
      }
155
    }
156
  }
157

    
158
  /**
159
   * Gets all the attached databases.
160
   *
161
   * @return array
162
   *   An array of attached database names.
163
   *
164
   * @see DatabaseConnection_sqlite::__construct().
165
   */
166
  public function getAttachedDatabases() {
167
    return $this->attachedDatabases;
168
  }
169

    
170
  /**
171
   * SQLite compatibility implementation for the IF() SQL function.
172
   */
173
  public function sqlFunctionIf($condition, $expr1, $expr2 = NULL) {
174
    return $condition ? $expr1 : $expr2;
175
  }
176

    
177
  /**
178
   * SQLite compatibility implementation for the GREATEST() SQL function.
179
   */
180
  public function sqlFunctionGreatest() {
181
    $args = func_get_args();
182
    foreach ($args as $k => $v) {
183
      if (!isset($v)) {
184
        unset($args);
185
      }
186
    }
187
    if (count($args)) {
188
      return max($args);
189
    }
190
    else {
191
      return NULL;
192
    }
193
  }
194

    
195
  /**
196
   * SQLite compatibility implementation for the CONCAT() SQL function.
197
   */
198
  public function sqlFunctionConcat() {
199
    $args = func_get_args();
200
    return implode('', $args);
201
  }
202

    
203
  /**
204
   * SQLite compatibility implementation for the SUBSTRING() SQL function.
205
   */
206
  public function sqlFunctionSubstring($string, $from, $length) {
207
    return substr($string, $from - 1, $length);
208
  }
209

    
210
  /**
211
   * SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
212
   */
213
  public function sqlFunctionSubstringIndex($string, $delimiter, $count) {
214
    // If string is empty, simply return an empty string.
215
    if (empty($string)) {
216
      return '';
217
    }
218
    $end = 0;
219
    for ($i = 0; $i < $count; $i++) {
220
      $end = strpos($string, $delimiter, $end + 1);
221
      if ($end === FALSE) {
222
        $end = strlen($string);
223
      }
224
    }
225
    return substr($string, 0, $end);
226
  }
227

    
228
  /**
229
   * SQLite compatibility implementation for the RAND() SQL function.
230
   */
231
  public function sqlFunctionRand($seed = NULL) {
232
    if (isset($seed)) {
233
      mt_srand($seed);
234
    }
235
    return mt_rand() / mt_getrandmax();
236
  }
237

    
238
  /**
239
   * SQLite-specific implementation of DatabaseConnection::prepare().
240
   *
241
   * We don't use prepared statements at all at this stage. We just create
242
   * a DatabaseStatement_sqlite object, that will create a PDOStatement
243
   * using the semi-private PDOPrepare() method below.
244
   */
245
  public function prepare($query, $options = array()) {
246
    return new DatabaseStatement_sqlite($this, $query, $options);
247
  }
248

    
249
  /**
250
   * NEVER CALL THIS FUNCTION: YOU MIGHT DEADLOCK YOUR PHP PROCESS.
251
   *
252
   * This is a wrapper around the parent PDO::prepare method. However, as
253
   * the PDO SQLite driver only closes SELECT statements when the PDOStatement
254
   * destructor is called and SQLite does not allow data change (INSERT,
255
   * UPDATE etc) on a table which has open SELECT statements, you should never
256
   * call this function and keep a PDOStatement object alive as that can lead
257
   * to a deadlock. This really, really should be private, but as
258
   * DatabaseStatement_sqlite needs to call it, we have no other choice but to
259
   * expose this function to the world.
260
   */
261
  public function PDOPrepare($query, array $options = array()) {
262
    return parent::prepare($query, $options);
263
  }
264

    
265
  public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
266
    return $this->query($query . ' LIMIT ' . (int) $from . ', ' . (int) $count, $args, $options);
267
  }
268

    
269
  public function queryTemporary($query, array $args = array(), array $options = array()) {
270
    // Generate a new temporary table name and protect it from prefixing.
271
    // SQLite requires that temporary tables to be non-qualified.
272
    $tablename = $this->generateTemporaryTableName();
273
    $prefixes = $this->prefixes;
274
    $prefixes[$tablename] = '';
275
    $this->setPrefix($prefixes);
276

    
277
    $this->query('CREATE TEMPORARY TABLE ' . $tablename . ' AS ' . $query, $args, $options);
278
    return $tablename;
279
  }
280

    
281
  public function driver() {
282
    return 'sqlite';
283
  }
284

    
285
  public function databaseType() {
286
    return 'sqlite';
287
  }
288

    
289
  public function mapConditionOperator($operator) {
290
    // We don't want to override any of the defaults.
291
    static $specials = array(
292
      'LIKE' => array('postfix' => " ESCAPE '\\'"),
293
      'NOT LIKE' => array('postfix' => " ESCAPE '\\'"),
294
    );
295
    return isset($specials[$operator]) ? $specials[$operator] : NULL;
296
  }
297

    
298
  public function prepareQuery($query) {
299
    return $this->prepare($this->prefixTables($query));
300
  }
301

    
302
  public function nextId($existing_id = 0) {
303
    $transaction = $this->startTransaction();
304
    // We can safely use literal queries here instead of the slower query
305
    // builder because if a given database breaks here then it can simply
306
    // override nextId. However, this is unlikely as we deal with short strings
307
    // and integers and no known databases require special handling for those
308
    // simple cases. If another transaction wants to write the same row, it will
309
    // wait until this transaction commits.
310
    $stmt = $this->query('UPDATE {sequences} SET value = GREATEST(value, :existing_id) + 1', array(
311
      ':existing_id' => $existing_id,
312
    ));
313
    if (!$stmt->rowCount()) {
314
      $this->query('INSERT INTO {sequences} (value) VALUES (:existing_id + 1)', array(
315
        ':existing_id' => $existing_id,
316
      ));
317
    }
318
    // The transaction gets committed when the transaction object gets destroyed
319
    // because it gets out of scope.
320
    return $this->query('SELECT value FROM {sequences}')->fetchField();
321
  }
322

    
323
  public function rollback($savepoint_name = 'drupal_transaction') {
324
    if ($this->savepointSupport) {
325
      return parent::rollBack($savepoint_name);
326
    }
327

    
328
    if (!$this->inTransaction()) {
329
      throw new DatabaseTransactionNoActiveException();
330
    }
331
    // A previous rollback to an earlier savepoint may mean that the savepoint
332
    // in question has already been rolled back.
333
    if (!in_array($savepoint_name, $this->transactionLayers)) {
334
      return;
335
    }
336

    
337
    // We need to find the point we're rolling back to, all other savepoints
338
    // before are no longer needed.
339
    while ($savepoint = array_pop($this->transactionLayers)) {
340
      if ($savepoint == $savepoint_name) {
341
        // Mark whole stack of transactions as needed roll back.
342
        $this->willRollback = TRUE;
343
        // If it is the last the transaction in the stack, then it is not a
344
        // savepoint, it is the transaction itself so we will need to roll back
345
        // the transaction rather than a savepoint.
346
        if (empty($this->transactionLayers)) {
347
          break;
348
        }
349
        return;
350
      }
351
    }
352
    if ($this->supportsTransactions()) {
353
      PDO::rollBack();
354
    }
355
  }
356

    
357
  public function pushTransaction($name) {
358
    if ($this->savepointSupport) {
359
      return parent::pushTransaction($name);
360
    }
361
    if (!$this->supportsTransactions()) {
362
      return;
363
    }
364
    if (isset($this->transactionLayers[$name])) {
365
      throw new DatabaseTransactionNameNonUniqueException($name . " is already in use.");
366
    }
367
    if (!$this->inTransaction()) {
368
      PDO::beginTransaction();
369
    }
370
    $this->transactionLayers[$name] = $name;
371
  }
372

    
373
  public function popTransaction($name) {
374
    if ($this->savepointSupport) {
375
      return parent::popTransaction($name);
376
    }
377
    if (!$this->supportsTransactions()) {
378
      return;
379
    }
380
    if (!$this->inTransaction()) {
381
      throw new DatabaseTransactionNoActiveException();
382
    }
383

    
384
    // Commit everything since SAVEPOINT $name.
385
    while($savepoint = array_pop($this->transactionLayers)) {
386
      if ($savepoint != $name) continue;
387

    
388
      // If there are no more layers left then we should commit or rollback.
389
      if (empty($this->transactionLayers)) {
390
        // If there was any rollback() we should roll back whole transaction.
391
        if ($this->willRollback) {
392
          $this->willRollback = FALSE;
393
          PDO::rollBack();
394
        }
395
        elseif (!PDO::commit()) {
396
          throw new DatabaseTransactionCommitFailedException();
397
        }
398
      }
399
      else {
400
        break;
401
      }
402
    }
403
  }
404

    
405
  public function utf8mb4IsActive() {
406
    return TRUE;
407
  }
408

    
409
  public function utf8mb4IsSupported() {
410
    return TRUE;
411
  }
412

    
413
}
414

    
415
/**
416
 * Specific SQLite implementation of DatabaseConnection.
417
 *
418
 * See DatabaseConnection_sqlite::PDOPrepare() for reasons why we must prefetch
419
 * the data instead of using PDOStatement.
420
 *
421
 * @see DatabaseConnection_sqlite::PDOPrepare()
422
 */
423
class DatabaseStatement_sqlite extends DatabaseStatementPrefetch implements Iterator, DatabaseStatementInterface {
424

    
425
  /**
426
   * SQLite specific implementation of getStatement().
427
   *
428
   * The PDO SQLite layer doesn't replace numeric placeholders in queries
429
   * correctly, and this makes numeric expressions (such as COUNT(*) >= :count)
430
   * fail. We replace numeric placeholders in the query ourselves to work
431
   * around this bug.
432
   *
433
   * See http://bugs.php.net/bug.php?id=45259 for more details.
434
   */
435
  protected function getStatement($query, &$args = array()) {
436
    if (count($args)) {
437
      // Check if $args is a simple numeric array.
438
      if (range(0, count($args) - 1) === array_keys($args)) {
439
        // In that case, we have unnamed placeholders.
440
        $count = 0;
441
        $new_args = array();
442
        foreach ($args as $value) {
443
          if (is_float($value) || is_int($value)) {
444
            if (is_float($value)) {
445
              // Force the conversion to float so as not to loose precision
446
              // in the automatic cast.
447
              $value = sprintf('%F', $value);
448
            }
449
            $query = substr_replace($query, $value, strpos($query, '?'), 1);
450
          }
451
          else {
452
            $placeholder = ':db_statement_placeholder_' . $count++;
453
            $query = substr_replace($query, $placeholder, strpos($query, '?'), 1);
454
            $new_args[$placeholder] = $value;
455
          }
456
        }
457
        $args = $new_args;
458
      }
459
      else {
460
        // Else, this is using named placeholders.
461
        foreach ($args as $placeholder => $value) {
462
          if (is_float($value) || is_int($value)) {
463
            if (is_float($value)) {
464
              // Force the conversion to float so as not to loose precision
465
              // in the automatic cast.
466
              $value = sprintf('%F', $value);
467
            }
468

    
469
            // We will remove this placeholder from the query as PDO throws an
470
            // exception if the number of placeholders in the query and the
471
            // arguments does not match.
472
            unset($args[$placeholder]);
473
            // PDO allows placeholders to not be prefixed by a colon. See
474
            // http://marc.info/?l=php-internals&m=111234321827149&w=2 for
475
            // more.
476
            if ($placeholder[0] != ':') {
477
              $placeholder = ":$placeholder";
478
            }
479
            // When replacing the placeholders, make sure we search for the
480
            // exact placeholder. For example, if searching for
481
            // ':db_placeholder_1', do not replace ':db_placeholder_11'.
482
            $query = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $query);
483
          }
484
        }
485
      }
486
    }
487

    
488
    return $this->dbh->PDOPrepare($query);
489
  }
490

    
491
  public function execute($args = array(), $options = array()) {
492
    try {
493
      $return = parent::execute($args, $options);
494
    }
495
    catch (PDOException $e) {
496
      if (!empty($e->errorInfo[1]) && $e->errorInfo[1] === 17) {
497
        // The schema has changed. SQLite specifies that we must resend the query.
498
        $return = parent::execute($args, $options);
499
      }
500
      else {
501
        // Rethrow the exception.
502
        throw $e;
503
      }
504
    }
505

    
506
    // In some weird cases, SQLite will prefix some column names by the name
507
    // of the table. We post-process the data, by renaming the column names
508
    // using the same convention as MySQL and PostgreSQL.
509
    $rename_columns = array();
510
    foreach ($this->columnNames as $k => $column) {
511
      // In some SQLite versions, SELECT DISTINCT(field) will return "(field)"
512
      // instead of "field".
513
      if (preg_match("/^\((.*)\)$/", $column, $matches)) {
514
        $rename_columns[$column] = $matches[1];
515
        $this->columnNames[$k] = $matches[1];
516
        $column = $matches[1];
517
      }
518

    
519
      // Remove "table." prefixes.
520
      if (preg_match("/^.*\.(.*)$/", $column, $matches)) {
521
        $rename_columns[$column] = $matches[1];
522
        $this->columnNames[$k] = $matches[1];
523
      }
524
    }
525
    if ($rename_columns) {
526
      // DatabaseStatementPrefetch already extracted the first row,
527
      // put it back into the result set.
528
      if (isset($this->currentRow)) {
529
        $this->data[0] = &$this->currentRow;
530
      }
531

    
532
      // Then rename all the columns across the result set.
533
      foreach ($this->data as $k => $row) {
534
        foreach ($rename_columns as $old_column => $new_column) {
535
          $this->data[$k][$new_column] = $this->data[$k][$old_column];
536
          unset($this->data[$k][$old_column]);
537
        }
538
      }
539

    
540
      // Finally, extract the first row again.
541
      $this->currentRow = $this->data[0];
542
      unset($this->data[0]);
543
    }
544

    
545
    return $return;
546
  }
547
}
548

    
549
/**
550
 * @} End of "addtogroup database".
551
 */