database.inc 87.8 KB
Newer Older
1
2
3
4
5
<?php
// $Id$

/**
 * @file
6
7
8
9
10
 * Core systems for the database layer.
 *
 * Classes required for basic functioning of the database system should be
 * placed in this file.  All utility functions should also be placed in this
 * file only, as they cannot auto-load the way classes can.
11
12
13
14
15
16
17
18
 */

/**
 * @defgroup database Database abstraction layer
 * @{
 * Allow the use of different database servers using the same code base.
 *
 * Drupal provides a database abstraction layer to provide developers with
19
 * the ability to support multiple database servers easily. The intent of
20
21
 * this layer is to preserve the syntax and power of SQL as much as possible,
 * but also allow developers a way to leverage more complex functionality in
22
 * a unified way. It also provides a structured interface for dynamically
23
24
25
26
27
28
29
 * constructing queries when appropriate, and enforcing security checks and
 * similar good practices.
 *
 * The system is built atop PHP's PDO (PHP Data Objects) database API and
 * inherits much of its syntax and semantics.
 *
 * Most Drupal database SELECT queries are performed by a call to db_query() or
30
31
32
33
 * db_query_range(). Module authors should also consider using the PagerDefault
 * Extender for queries that return results that need to be presented on
 * multiple pages, and the Tablesort Extender for generating appropriate queries
 * for sortable tables.
34
35
36
37
 *
 * For example, one might wish to return a list of the most recent 10 nodes
 * authored by a given user. Instead of directly issuing the SQL query
 * @code
38
 * SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;
39
40
41
 * @endcode
 * one would instead call the Drupal functions:
 * @code
42
 * $result = db_query_range('SELECT n.nid, n.title, n.created
43
 *   FROM {node} n WHERE n.uid = :uid', 0, 10, array(':uid' => $uid));
44
45
46
 * foreach($result as $record) {
 *   // Perform operations on $node->title, etc. here.
 * }
47
48
49
50
51
52
53
54
 * @endcode
 * Curly braces are used around "node" to provide table prefixing via
 * DatabaseConnection::prefixTables(). The explicit use of a user ID is pulled
 * out into an argument passed to db_query() so that SQL injection attacks
 * from user input can be caught and nullified. The LIMIT syntax varies between
 * database servers, so that is abstracted into db_query_range() arguments.
 * Finally, note the PDO-based ability to foreach() over the result set.
 *
55
 * All queries are passed as a prepared statement string. A
56
 * prepared statement is a "template" of a query that omits literal or variable
57
 * values in favor of placeholders. The values to place into those
58
 * placeholders are passed separately, and the database driver handles
59
 * inserting the values into the query in a secure fashion. That means you
60
 * should never quote or string-escape a value to be inserted into the query.
61
 *
62
 * There are two formats for placeholders: named and unnamed. Named placeholders
63
 * are strongly preferred in all cases as they are more flexible and
64
65
 * self-documenting. Named placeholders should start with a colon ":" and can be
 * followed by one or more letters, numbers or underscores.
66
 *
67
68
 * Named placeholders begin with a colon followed by a unique string. Example:
 * @code
69
 * SELECT nid, title FROM {node} WHERE uid=:uid;
70
 * @endcode
71
 *
72
 * ":uid" is a placeholder that will be replaced with a literal value when
73
74
 * the query is executed. A given placeholder label cannot be repeated in a
 * given query, even if the value should be the same. When using named
75
76
 * placeholders, the array of arguments to the query must be an associative
 * array where keys are a placeholder label (e.g., :uid) and the value is the
77
 * corresponding value to use. The array may be in any order.
78
 *
79
 * Unnamed placeholders are simply a question mark. Example:
80
 * @code
81
 * SELECT nid, title FROM {node} WHERE uid=?;
82
 * @endcode
83
 *
84
 * In this case, the array of arguments must be an indexed array of values to
85
86
 * use in the exact same order as the placeholders in the query.
 *
87
 * Note that placeholders should be a "complete" value. For example, when
88
 * running a LIKE query the SQL wildcard character, %, should be part of the
89
 * value, not the query itself. Thus, the following is incorrect:
90
 * @code
91
 * SELECT nid, title FROM {node} WHERE title LIKE :title%;
92
93
94
 * @endcode
 * It should instead read:
 * @code
95
 * SELECT nid, title FROM {node} WHERE title LIKE :title;
96
 * @endcode
97
98
 * and the value for :title should include a % as appropriate. Again, note the
 * lack of quotation marks around :title. Because the value is not inserted
99
 * into the query as one big string but as an explicitly separate value, the
100
 * database server knows where the query ends and a value begins. That is
101
 * considerably more secure against SQL injection than trying to remember
102
 * which values need quotation marks and string escaping and which don't.
103
 *
104
 * INSERT, UPDATE, and DELETE queries need special care in order to behave
105
 * consistently across all different databases. Therefore, they use a special
106
107
 * object-oriented API for defining a query structurally. For example, rather
 * than:
108
 * @code
109
 * INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body');
110
111
112
113
 * @endcode
 * one would instead write:
 * @code
 * $fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
114
 * db_insert('node')->fields($fields)->execute();
115
116
 * @endcode
 * This method allows databases that need special data type handling to do so,
117
 * while also allowing optimizations such as multi-insert queries. UPDATE and
118
 * DELETE queries have a similar pattern.
119
120
121
 *
 * Drupal also supports transactions, including a transparent fallback for
 * databases that do not support transactions. To start a new transaction,
122
 * simply call $txn = db_transaction(); in your own code. The transaction will
123
124
125
126
127
128
129
130
131
132
133
134
 * remain open for as long as the variable $txn remains in scope.  When $txn is
 * destroyed, the transaction will be committed.  If your transaction is nested
 * inside of another then Drupal will track each transaction and only commit
 * the outer-most transaction when the last transaction object goes out out of
 * scope, that is, all relevant queries completed successfully.
 *
 * Example:
 * @code
 * function my_transaction_function() {
 *   // The transaction opens here.
 *   $txn = db_transaction();
 *
135
136
137
138
139
140
141
142
143
 *   try {
 *     $id = db_insert('example')
 *       ->fields(array(
 *         'field1' => 'mystring',
 *         'field2' => 5,
 *       ))
 *       ->execute();
 *
 *     my_other_function($id);
144
 *
145
146
147
 *     return $id;
 *   }
 *   catch (Exception $e) {
148
 *     // Something went wrong somewhere, so roll back now.
149
 *     $txn->rollback();
150
151
 *     // Log the exception to watchdog.
 *     watchdog_exception('type', $e);
152
 *   }
153
 *
154
155
 *   // $txn goes out of scope here.  Unless the transaction was rolled back, it
 *   // gets automatically commited here.
156
157
158
159
160
161
162
163
164
165
166
167
168
 * }
 *
 * function my_other_function($id) {
 *   // The transaction is still open here.
 *
 *   if ($id % 2 == 0) {
 *     db_update('example')
 *       ->condition('id', $id)
 *       ->fields(array('field2' => 10))
 *       ->execute();
 *   }
 * }
 * @endcode
169
170
171
172
173
174
 */


/**
 * Base Database API class.
 *
175
176
177
178
 * This class provides a Drupal-specific extension of the PDO database
 * abstraction class in PHP. Every database driver implementation must provide a
 * concrete implementation of it to support special handling required by that
 * database.
179
 *
180
 * @see http://php.net/manual/en/book.pdo.php
181
182
183
 */
abstract class DatabaseConnection extends PDO {

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
  /**
   * The database target this connection is for.
   *
   * We need this information for later auditing and logging.
   *
   * @var string
   */
  protected $target = NULL;

  /**
   * The current database logging object for this connection.
   *
   * @var DatabaseLog
   */
  protected $logger = NULL;

200
  /**
201
   * Tracks the number of "layers" of transactions currently active.
202
203
204
205
206
   *
   * On many databases transactions cannot nest.  Instead, we track
   * nested calls to transactions and collapse them into a single
   * transaction.
   *
207
   * @var array
208
   */
209
  protected $transactionLayers = array();
210

211
  /**
212
   * Index of what driver-specific class to use for various operations.
213
   *
214
   * @var array
215
   */
216
  protected $driverClasses = array();
217

218
219
220
221
222
  /**
   * The name of the Statement class for this connection.
   *
   * @var string
   */
223
224
225
226
227
228
229
230
  protected $statementClass = 'DatabaseStatementBase';

  /**
   * Whether this database connection supports transactions.
   *
   * @var bool
   */
  protected $transactionSupport = TRUE;
231

232
233
234
235
236
237
238
239
240
  /**
   * Whether this database connection supports transactional DDL.
   *
   * Set to FALSE by default because few databases support this feature.
   *
   * @var bool
   */
  protected $transactionalDDLSupport = FALSE;

241
242
243
244
245
246
247
  /**
   * An index used to generate unique temporary table names.
   *
   * @var integer
   */
  protected $temporaryNameIndex = 0;

248
249
250
251
252
253
254
  /**
   * The connection information for this connection object.
   *
   * @var array
   */
  protected $connectionOptions = array();

255
256
257
258
259
260
261
  /**
   * The schema object for this connection.
   *
   * @var object
   */
  protected $schema = NULL;

262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
  /**
   * The default prefix used by this database connection.
   *
   * Separated from the other prefixes for performance reasons.
   *
   * @var string
   */
  protected $defaultPrefix = '';

  /**
   * The non-default prefixes used by this database connection.
   *
   * @var array
   */
  protected $prefixes = array();

278
  function __construct($dsn, $username, $password, $driver_options = array()) {
279
280
281
    // Initialize and prepare the connection prefix.
    $this->setPrefix(isset($this->connectionOptions['prefix']) ? $this->connectionOptions['prefix'] : '');

282
283
    // Because the other methods don't seem to work right.
    $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
284

285
    // Call PDO::__construct and PDO::setAttribute.
286
    parent::__construct($dsn, $username, $password, $driver_options);
287
288

    // Set a specific PDOStatement class if the driver requires that.
289
    if (!empty($this->statementClass)) {
290
      $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($this->statementClass, array($this)));
291
    }
292
293
294
  }

  /**
295
   * Returns the default query options for any given query.
296
   *
297
   * A given query can be customized with a number of option flags in an
298
299
   * associative array:
   * - target: The database "target" against which to execute a query. Valid
300
301
   *   values are "default" or "slave". The system will first try to open a
   *   connection to a database specified with the user-supplied key. If one
302
303
   *   is not available, it will silently fall back to the "default" target.
   *   If multiple databases connections are specified with the same target,
304
   *   one will be selected at random for the duration of the request.
305
   * - fetch: This element controls how rows from a result set will be
306
307
308
309
310
   *   returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH,
   *   PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a
   *   class. If a string is specified, each record will be fetched into a new
   *   object of that class. The behavior of all other values is defined by PDO.
   *   See http://www.php.net/PDOStatement-fetch
311
   * - return: Depending on the type of query, different return values may be
312
313
   *   meaningful. This directive instructs the system which type of return
   *   value is desired. The system will generally set the correct value
314
   *   automatically, so it is extremely rare that a module developer will ever
315
316
   *   need to specify this value. Setting it incorrectly will likely lead to
   *   unpredictable results or fatal errors. Legal values include:
317
   *   - Database::RETURN_STATEMENT: Return the prepared statement object for
318
319
320
   *     the query. This is usually only meaningful for SELECT queries, where
   *     the statement object is how one accesses the result set returned by the
   *     query.
321
   *   - Database::RETURN_AFFECTED: Return the number of rows affected by an
322
323
   *     UPDATE or DELETE query. Be aware that means the number of rows actually
   *     changed, not the number of rows matched by the WHERE clause.
324
   *   - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
325
326
   *     created by an INSERT statement on a table that contains a serial
   *     column.
327
   *   - Database::RETURN_NULL: Do not return anything, as there is no
328
   *     meaningful value to return. That is the case for INSERT queries on
329
   *     tables that do not contain a serial column.
330
   * - throw_exception: By default, the database system will catch any errors
331
   *   on a query as an Exception, log it, and then rethrow it so that code
332
   *   further up the call chain can take an appropriate action. To suppress
333
334
   *   that behavior and simply return NULL on failure, set this option to
   *   FALSE.
335
336
337
338
339
340
341
342
343
344
345
346
347
   *
   * @return
   *   An array of default query options.
   */
  protected function defaultOptions() {
    return array(
      'target' => 'default',
      'fetch' => PDO::FETCH_OBJ,
      'return' => Database::RETURN_STATEMENT,
      'throw_exception' => TRUE,
    );
  }

348
  /**
349
   * Returns the connection information for this connection object.
350
351
352
353
354
355
356
357
358
359
360
361
362
363
   *
   * Note that Database::getConnectionInfo() is for requesting information
   * about an arbitrary database connection that is defined. This method
   * is for requesting the connection information of this specific
   * open connection object.
   *
   * @return
   *   An array of the connection information. The exact list of
   *   properties is driver-dependent.
   */
  public function getConnectionOptions() {
    return $this->connectionOptions;
  }

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
  /**
   * Preprocess the prefixes used by this database connection.
   *
   * @param $prefix
   *   The prefixes, in any of the multiple forms documented in
   *   default.settings.php.
   */
  protected function setPrefix($prefix) {
    if (is_array($prefix)) {
      $this->defaultPrefix = isset($prefix['default']) ? $prefix['default'] : '';
      unset($prefix['default']);
      $this->prefixes = $prefix;
    }
    else {
      $this->defaultPrefix = $prefix;
      $this->prefixes = array();
    }
  }

383
  /**
384
   * Appends a database prefix to all tables in a query.
385
386
387
   *
   * Queries sent to Drupal should wrap all table names in curly brackets. This
   * function searches for this syntax and adds Drupal's table prefix to all
388
   * tables, allowing Drupal to coexist with other systems in the same database
389
   * and/or schema if necessary.
390
391
392
   *
   * @param $sql
   *   A string containing a partial or entire SQL query.
393
   *
394
395
396
   * @return
   *   The properly-prefixed string.
   */
397
  public function prefixTables($sql) {
398
399
400
    // Replace specific table prefixes first.
    foreach ($this->prefixes as $key => $val) {
      $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
401
    }
402
403
    // Then replace remaining tables with the default prefix.
    return strtr($sql, array('{' => $this->defaultPrefix , '}' => ''));
404
405
  }

406
407
408
409
410
411
412
  /**
   * Find the prefix for a table.
   *
   * This function is for when you want to know the prefix of a table. This
   * is not used in prefixTables due to performance reasons.
   */
  public function tablePrefix($table = 'default') {
413
414
415
416
417
    if (isset($this->prefixes[$table])) {
      return $this->prefixes[$table];
    }
    else {
      return $this->defaultPrefix;
418
419
420
    }
  }

421
  /**
422
   * Prepares a query string and returns the prepared statement.
423
   *
424
   * This method caches prepared statements, reusing them when
425
   * possible. It also prefixes tables names enclosed in curly-braces.
426
427
428
429
   *
   * @param $query
   *   The query string as SQL, with curly-braces surrounding the
   *   table names.
430
   *
431
   * @return DatabaseStatementInterface
432
433
   *   A PDO prepared statement ready for its execute() method.
   */
434
  public function prepareQuery($query) {
435
    $query = $this->prefixTables($query);
436
437
438

    // Call PDO::prepare.
    return parent::prepare($query);
439
440
  }

441
  /**
442
   * Tells this connection object what its target value is.
443
   *
444
   * This is needed for logging and auditing. It's sloppy to do in the
445
   * constructor because the constructor for child classes has a different
446
   * signature. We therefore also ensure that this function is only ever
447
448
449
   * called once.
   *
   * @param $target
450
   *   The target this connection is for. Set to NULL (default) to disable
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
   *   logging entirely.
   */
  public function setTarget($target = NULL) {
    if (!isset($this->target)) {
      $this->target = $target;
    }
  }

  /**
   * Returns the target this connection is associated with.
   *
   * @return
   *   The target string of this connection.
   */
  public function getTarget() {
    return $this->target;
  }

  /**
470
   * Associates a logging object with this connection.
471
472
473
474
475
476
477
478
479
   *
   * @param $logger
   *   The logging object we want to use.
   */
  public function setLogger(DatabaseLog $logger) {
    $this->logger = $logger;
  }

  /**
480
   * Gets the current logging object for this connection.
481
   *
482
   * @return DatabaseLog
483
   *   The current logging object for this connection. If there isn't one,
484
485
486
487
488
489
   *   NULL is returned.
   */
  public function getLogger() {
    return $this->logger;
  }

490
  /**
491
   * Creates the appropriate sequence name for a given table and serial field.
492
   *
493
   * This information is exposed to all database drivers, although it is only
494
   * useful on some of them. This method is table prefix-aware.
495
   *
496
497
498
499
   * @param $table
   *   The table name to use for the sequence.
   * @param $field
   *   The field name to use for the sequence.
500
   *
501
502
503
504
   * @return
   *   A table prefix-parsed string for the sequence name.
   */
  public function makeSequenceName($table, $field) {
505
    return $this->prefixTables('{' . $table . '}_' . $field . '_seq');
506
  }
507

508
509
510
  /**
   * Executes a query string against the database.
   *
511
512
513
   * This method provides a central handler for the actual execution of every
   * query. All queries executed by Drupal are executed as PDO prepared
   * statements.
514
   *
515
   * @param $query
516
517
   *   The query to execute. In most cases this will be a string containing
   *   an SQL query with placeholders. An already-prepared instance of
518
519
520
   *   DatabaseStatementInterface may also be passed in order to allow calling
   *   code to manually bind variables to a query. If a
   *   DatabaseStatementInterface is passed, the $args array will be ignored.
521
   *   It is extremely rare that module code will need to pass a statement
522
   *   object to this method. It is used primarily for database drivers for
523
524
   *   databases that require special LOB field handling.
   * @param $args
525
   *   An array of arguments for the prepared statement. If the prepared
526
527
528
   *   statement uses ? placeholders, this array must be an indexed array.
   *   If it contains named placeholders, it must be an associative array.
   * @param $options
529
   *   An associative array of options to control how the query is run. See
530
   *   the documentation for DatabaseConnection::defaultOptions() for details.
531
   *
532
   * @return DatabaseStatementInterface
533
   *   This method will return one of: the executed statement, the number of
534
   *   rows affected by the query (not the number matched), or the generated
535
536
537
538
539
   *   insert IT of the last query, depending on the value of
   *   $options['return']. Typically that value will be set by default or a
   *   query builder and should not be set by a user. If there is an error,
   *   this method will return NULL and may throw an exception if
   *   $options['throw_exception'] is TRUE.
540
   */
541
  public function query($query, array $args = array(), $options = array()) {
542
543
544

    // Use default values if not already set.
    $options += $this->defaultOptions();
545

546
547
    try {
      // We allow either a pre-bound statement object or a literal string.
548
549
      // In either case, we want to end up with an executed statement object,
      // which we pass to PDOStatement::execute.
550
      if ($query instanceof DatabaseStatementInterface) {
551
552
553
554
        $stmt = $query;
        $stmt->execute(NULL, $options);
      }
      else {
555
556
        $this->expandArguments($query, $args);
        $stmt = $this->prepareQuery($query);
557
558
        $stmt->execute($args, $options);
      }
559

560
      // Depending on the type of query we may need to return a different value.
561
562
      // See DatabaseConnection::defaultOptions() for a description of each
      // value.
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
      switch ($options['return']) {
        case Database::RETURN_STATEMENT:
          return $stmt;
        case Database::RETURN_AFFECTED:
          return $stmt->rowCount();
        case Database::RETURN_INSERT_ID:
          return $this->lastInsertId();
        case Database::RETURN_NULL:
          return;
        default:
          throw new PDOException('Invalid return directive: ' . $options['return']);
      }
    }
    catch (PDOException $e) {
      if ($options['throw_exception']) {
578
        // Add additional debug information.
579
        if ($query instanceof DatabaseStatementInterface) {
580
          $e->query_string = $stmt->getQueryString();
581
582
        }
        else {
583
          $e->query_string = $query;
584
        }
585
586
        $e->args = $args;
        throw $e;
587
588
589
590
591
      }
      return NULL;
    }
  }

592
  /**
593
   * Expands out shorthand placeholders.
594
   *
595
596
   * Drupal supports an alternate syntax for doing arrays of values. We
   * therefore need to expand them out into a full, executable query string.
597
598
599
600
601
   *
   * @param $query
   *   The query string to modify.
   * @param $args
   *   The arguments for the query.
602
   *
603
604
605
606
607
608
   * @return
   *   TRUE if the query was modified, FALSE otherwise.
   */
  protected function expandArguments(&$query, &$args) {
    $modified = FALSE;

609
610
611
612
613
614
615
616
617
618
619
    // If the placeholder value to insert is an array, assume that we need
    // to expand it out into a comma-delimited set of placeholders.
    foreach (array_filter($args, 'is_array') as $key => $data) {
      $new_keys = array();
      foreach ($data as $i => $value) {
        // This assumes that there are no other placeholders that use the same
        // name.  For example, if the array placeholder is defined as :example
        // and there is already an :example_2 placeholder, this will generate
        // a duplicate key.  We do not account for that as the calling code
        // is already broken if that happens.
        $new_keys[$key . '_' . $i] = $value;
620
      }
621
622
623
624

      // Update the query with the new placeholders.
      // preg_replace is necessary to ensure the replacement does not affect
      // placeholders that start with the same exact text. For example, if the
625
      // query contains the placeholders :foo and :foobar, and :foo has an
626
627
628
629
630
631
632
633
634
635
      // array of values, using str_replace would affect both placeholders,
      // but using the following preg_replace would only affect :foo because
      // it is followed by a non-word character.
      $query = preg_replace('#' . $key . '\b#', implode(', ', array_keys($new_keys)), $query);

      // Update the args array with the new placeholders.
      unset($args[$key]);
      $args += $new_keys;

      $modified = TRUE;
636
637
638
639
640
    }

    return $modified;
  }

641
642
643
644
645
646
647
648
  /**
   * Gets the driver-specific override class if any for the specified class.
   *
   * @param string $class
   *   The class for which we want the potentially driver-specific class.
   * @return string
   *   The name of the class that should be used for this driver.
   */
649
  public function getDriverClass($class) {
650
651
652
653
654
655
656
657
658
    if (empty($this->driverClasses[$class])) {
      $this->driverClasses[$class] = $class . '_' . $this->driver();
      if (!class_exists($this->driverClasses[$class])) {
        $this->driverClasses[$class] = $class;
      }
    }
    return $this->driverClasses[$class];
  }

659
  /**
660
   * Prepares and returns a SELECT query object with the specified ID.
661
662
663
   *
   * @param $table
   *   The base table for this query, that is, the first table in the FROM
664
   *   clause. This table will also be used as the "base" table for query_alter
665
666
667
668
669
   *   hook implementations.
   * @param $alias
   *   The alias of the base table of this query.
   * @param $options
   *   An array of options on the query.
670
   *
671
   * @return SelectQueryInterface
672
673
674
675
676
   *   An appropriate SelectQuery object for this database connection. Note that
   *   it may be a driver-specific subclass of SelectQuery, depending on the
   *   driver.
   *
   * @see SelectQuery
677
   */
678
  public function select($table, $alias = NULL, array $options = array()) {
679
    $class = $this->getDriverClass('SelectQuery');
680
    return new $class($table, $alias, $this, $options);
681
682
683
  }

  /**
684
   * Prepares and returns an INSERT query object with the specified ID.
685
686
687
   *
   * @param $options
   *   An array of options on the query.
688
   *
689
   * @return InsertQuery
690
   *   A new InsertQuery object.
691
692
   *
   * @see InsertQuery
693
   */
694
  public function insert($table, array $options = array()) {
695
    $class = $this->getDriverClass('InsertQuery');
696
    return new $class($this, $table, $options);
697
698
699
  }

  /**
700
   * Prepares and returns a MERGE query object with the specified ID.
701
702
703
   *
   * @param $options
   *   An array of options on the query.
704
   *
705
   * @return MergeQuery
706
   *   A new MergeQuery object.
707
708
   *
   * @see MergeQuery
709
   */
710
  public function merge($table, array $options = array()) {
711
    $class = $this->getDriverClass('MergeQuery');
712
    return new $class($this, $table, $options);
713
714
  }

715

716
  /**
717
   * Prepares and returns an UPDATE query object with the specified ID.
718
719
720
   *
   * @param $options
   *   An array of options on the query.
721
   *
722
   * @return UpdateQuery
723
   *   A new UpdateQuery object.
724
725
   *
   * @see UpdateQuery
726
   */
727
  public function update($table, array $options = array()) {
728
    $class = $this->getDriverClass('UpdateQuery');
729
    return new $class($this, $table, $options);
730
731
732
  }

  /**
733
   * Prepares and returns a DELETE query object with the specified ID.
734
735
736
   *
   * @param $options
   *   An array of options on the query.
737
   *
738
   * @return DeleteQuery
739
   *   A new DeleteQuery object.
740
741
   *
   * @see DeleteQuery
742
   */
743
  public function delete($table, array $options = array()) {
744
    $class = $this->getDriverClass('DeleteQuery');
745
    return new $class($this, $table, $options);
746
747
  }

748
  /**
749
   * Prepares and returns a TRUNCATE query object.
750
751
752
   *
   * @param $options
   *   An array of options on the query.
753
   *
754
   * @return TruncateQuery
755
756
757
   *   A new TruncateQuery object.
   *
   * @see TruncateQuery
758
759
   */
  public function truncate($table, array $options = array()) {
760
    $class = $this->getDriverClass('TruncateQuery');
761
762
763
    return new $class($this, $table, $options);
  }

764
  /**
765
   * Returns a DatabaseSchema object for manipulating the schema.
766
767
768
   *
   * This method will lazy-load the appropriate schema library file.
   *
769
   * @return DatabaseSchema
770
771
772
   *   The DatabaseSchema object for this connection.
   */
  public function schema() {
773
    if (empty($this->schema)) {
774
      $class = $this->getDriverClass('DatabaseSchema');
775
776
777
      if (class_exists($class)) {
        $this->schema = new $class($this);
      }
778
    }
779
    return $this->schema;
780
781
782
783
784
785
786
787
788
789
790
791
792
  }

  /**
   * Escapes a table name string.
   *
   * Force all table names to be strictly alphanumeric-plus-underscore.
   * For some database drivers, it may also wrap the table name in
   * database-specific escape characters.
   *
   * @return
   *   The sanitized table name string.
   */
  public function escapeTable($table) {
793
    return preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
794
795
  }

796
797
798
799
800
801
802
803
804
805
806
807
808
809
  /**
   * Escapes a field name string.
   *
   * Force all field names to be strictly alphanumeric-plus-underscore.
   * For some database drivers, it may also wrap the field name in
   * database-specific escape characters.
   *
   * @return
   *   The sanitized field name string.
   */
  public function escapeField($field) {
    return preg_replace('/[^A-Za-z0-9_.]+/', '', $field);
  }

810
  /**
811
   * Escapes characters that work as wildcard characters in a LIKE pattern.
812
813
   *
   * The wildcard characters "%" and "_" as well as backslash are prefixed with
814
   * a backslash. Use this to do a search for a verbatim string without any
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
   * wildcard behavior.
   *
   * For example, the following does a case-insensitive query for all rows whose
   * name starts with $prefix:
   * @code
   * $result = db_query(
   *   'SELECT * FROM person WHERE name LIKE :pattern',
   *   array(':pattern' => db_like($prefix) . '%')
   * );
   * @endcode
   *
   * Backslash is defined as escape character for LIKE patterns in
   * DatabaseCondition::mapConditionOperator().
   *
   * @param $string
   *   The string to escape.
831
   *
832
833
834
835
836
837
838
   * @return
   *   The escaped string.
   */
  public function escapeLike($string) {
    return addcslashes($string, '\%_');
  }

839
  /**
840
   * Determines if there is an active transaction open.
841
842
843
844
845
   *
   * @return
   *   TRUE if we're currently in a transaction, FALSE otherwise.
   */
  public function inTransaction() {
846
847
848
849
850
851
852
853
    return ($this->transactionDepth() > 0);
  }

  /**
   * Determines current transaction depth.
   */
  public function transactionDepth() {
    return count($this->transactionLayers);
854
855
  }

856
857
858
  /**
   * Returns a new DatabaseTransaction object on this connection.
   *
859
860
861
   * @param $name
   *   Optional name of the savepoint.
   *
862
863
   * @see DatabaseTransaction
   */
864
  public function startTransaction($name = '') {
865
866
    $class = $this->getDriverClass('DatabaseTransaction');
    return new $class($this, $name);
867
868
  }

869
  /**
870
   * Rolls back the transaction entirely or to a named savepoint.
871
872
   *
   * This method throws an exception if no transaction is active.
873
   *
874
875
876
   * @param $savepoint_name
   *   The name of the savepoint. The default, 'drupal_transaction', will roll
   *   the entire transaction back.
877
878
879
   *
   * @see DatabaseTransaction::rollback()
   */
880
  public function rollback($savepoint_name = 'drupal_transaction') {
881
882
883
    if (!$this->supportsTransactions()) {
      return;
    }
884
885
886
887
888
889
890
    if (!$this->inTransaction()) {
      throw new DatabaseTransactionNoActiveException();
    }
    // A previous rollback to an earlier savepoint may mean that the savepoint
    // in question has already been rolled back.
    if (!in_array($savepoint_name, $this->transactionLayers)) {
      return;
891
892
    }

893
894
895
896
897
898
899
900
901
902
903
904
905
906
    // We need to find the point we're rolling back to, all other savepoints
    // before are no longer needed.
    while ($savepoint = array_pop($this->transactionLayers)) {
      if ($savepoint == $savepoint_name) {
        // If it is the last the transaction in the stack, then it is not a
        // savepoint, it is the transaction itself so we will need to roll back
        // the transaction rather than a savepoint.
        if (empty($this->transactionLayers)) {
          break;
        }
        $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint);
        return;
      }
    }
907
    parent::rollBack();
908
909
910
911
912
913
914
915
916
  }

  /**
   * Increases the depth of transaction nesting.
   *
   * If no transaction is already active, we begin a new transaction.
   *
   * @see DatabaseTransaction
   */
917
918
919
920
921
922
923
924
925
926
927
  public function pushTransaction($name) {
    if (!$this->supportsTransactions()) {
      return;
    }
    if (isset($this->transactionLayers[$name])) {
      throw new DatabaseTransactionNameNonUniqueException($name . " is already in use.");
    }
    // If we're already in a transaction then we want to create a savepoint
    // rather than try to create another transaction.
    if ($this->inTransaction()) {
      $this->query('SAVEPOINT ' . $name);
928
    }
929
930
931
932
    else {
      parent::beginTransaction();
    }
    $this->transactionLayers[$name] = $name;
933
934
935
  }

  /**
936
   * Decreases the depth of transaction nesting.
937
   *
938
939
940
941
942
943
   * If we pop off the last transaction layer, then we either commit or roll
   * back the transaction as necessary. If no transaction is active, we return
   * because the transaction may have manually been rolled back.
   *
   * @param $name
   *   The name of the savepoint
944
945
946
   *
   * @see DatabaseTransaction
   */
947
948
949
950
951
952
  public function popTransaction($name) {
    if (!$this->supportsTransactions()) {
      return;
    }
    if (!$this->inTransaction()) {
      throw new DatabaseTransactionNoActiveException();
953
954
    }

955
956
957
    // Commit everything since SAVEPOINT $name.
    while($savepoint = array_pop($this->transactionLayers)) {
      if ($savepoint != $name) continue;
958

959
960
961
962
      // If there are no more layers left then we should commit.
      if (empty($this->transactionLayers)) {
        if (!parent::commit()) {
          throw new DatabaseTransactionCommitFailedException();
963
        }
964
      }
965
966
967
      else {
        $this->query('RELEASE SAVEPOINT ' . $name);
        break;
968
969
970
971
      }
    }
  }

972
973
974
975
  /**
   * Runs a limited-range query on this database object.
   *
   * Use this as a substitute for ->query() when a subset of the query is to be
976
977
978
   * returned. User-supplied arguments to the query should be passed in as
   * separate parameters so that they can be properly escaped to avoid SQL
   * injection attacks.
979
980
981
982
983
984
985
986
987
988
989
   *
   * @param $query
   *   A string containing an SQL query.
   * @param $args
   *   An array of values to substitute into the query at placeholder markers.
   * @param $from
   *   The first result row to return.
   * @param $count
   *   The maximum number of result rows to return.
   * @param $options
   *   An array of options on the query.
990
   *
991
   * @return DatabaseStatementInterface
992
993
994
   *   A database query result resource, or NULL if the query was not executed
   *   correctly.
   */
995
  abstract public function queryRange($query, $from, $count, array $args = array(), array $options = array());
996

997
  /**
998
   * Generates a temporary table name.
999
1000
1001
1002
1003
1004
1005
1006
   *
   * @return
   *   A table name.
   */
  protected function generateTemporaryTableName() {
    return "db_temporary_" . $this->temporaryNameIndex++;
  }

1007
1008
1009
1010
1011
  /**
   * Runs a SELECT query and stores its results in a temporary table.
   *
   * Use this as a substitute for ->query() when the results need to stored
   * in a temporary table. Temporary tables exist for the duration of the page
1012
1013
1014
   * request. User-supplied arguments to the query should be passed in as
   * separate parameters so that they can be properly escaped to avoid SQL
   * injection attacks.
1015
1016
1017
1018
1019
1020
1021
1022
   *
   * Note that if you need to know how many results were returned, you should do
   * a SELECT COUNT(*) on the temporary table afterwards.
   *
   * @param $query
   *   A string containing a normal SELECT SQL query.
   * @param $args
   *   An array of values to substitute into the query at placeholder markers.
1023
   * @param $options
1024
   *   An associative array of options to control how the query is run. See
1025
   *   the documentation for DatabaseConnection::defaultOptions() for details.
1026
   *
1027
   * @return
1028
   *   The name of the temporary table.
1029
   */
1030
  abstract function queryTemporary($query, array $args = array(), array $options = array());
1031
1032
1033
1034

  /**
   * Returns the type of database driver.
   *
1035
1036
1037
1038
   * This is not necessarily the same as the type of the database itself. For
   * instance, there could be two MySQL drivers, mysql and mysql_mock. This
   * function would return different values for each, but both would return
   * "mysql" for databaseType().
1039
1040
1041
1042
   */
  abstract public function driver();

  /**
1043
   * Determines if this driver supports transactions.
1044
1045
1046
   *
   * @return
   *   TRUE if this connection supports transactions, FALSE otherwise.
1047
   */
1048
  public function supportsTransactions() {
1049
1050
1051
1052
    return $this->transactionSupport;
  }

  /**
1053
   * Determines if this driver supports transactional DDL.
1054
1055
1056
1057
   *
   * DDL queries are those that change the schema, such as ALTER queries.
   *
   * @return
1058
1059
   *   TRUE if this connection supports transactions for DDL queries, FALSE
   *   otherwise.
1060
1061
1062
   */
  public function supportsTransactionalDDL() {
    return $this->transactionalDDLSupport;
1063
  }
1064
1065
1066
1067
1068
1069

  /**
   * Returns the type of the database being accessed.
   */
  abstract public function databaseType();

1070

1071
1072
1073
1074
  /**
   * Gets any special processing requirements for the condition operator.
   *
   * Some condition types require special processing, such as IN, because
1075
1076
   * the value data they pass in is not a simple value. This is a simple
   * overridable lookup function. Database connections should define only
1077
1078
1079
   * those operators they wish to be handled differently than the default.
   *
   * @param $operator
1080
   *   The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
1081
   *
1082
1083
   * @return
   *   The extra handling directives for the specified operator, or NULL.
1084
1085
   *
   * @see DatabaseCondition::compile()
1086
1087
   */
  abstract public function mapConditionOperator($operator);
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099

  /**
   * Throws an exception to deny direct access to transaction commits.
   *
   * We do not want to allow users to commit transactions at any time, only
   * by destroying the transaction object or allowing it to go out of scope.
   * A direct commit bypasses all of the safety checks we've built on top of
   * PDO's transaction routines.
   *
   * @see DatabaseTransaction
   */
  public function commit() {
1100
    throw new DatabaseTransactionExplicitCommitNotAllowedException();
1101
  }
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114

  /**
   * Retrieves an unique id from a given sequence.
   *
   * Use this function if for some reason you can't use a serial field. For
   * example, MySQL has no ways of reading of the current value of a sequence
   * and PostgreSQL can not advance the sequence to be larger than a given
   * value. Or sometimes you just need a unique integer.
   *
   * @param $existing_id
   *   After a database import, it might be that the sequences table is behind,
   *   so by passing in the maximum existing id, it can be assured that we
   *   never issue the same id.
1115
   *
1116
1117
1118
1119
   * @return
   *   An integer number larger than any number returned by earlier calls and
   *   also larger than the $existing_id if one was passed in.
   */
1120
  abstract public function nextId($existing_id = 0);
1121
1122
1123
1124
1125
}

/**
 * Primary front-controller for the database system.
 *
1126
 * This class is uninstantiatable and un-extendable. It acts to encapsulate
1127
1128
1129
1130
1131
1132
1133
 * all control and shepherding of database connections into a single location
 * without the use of globals.
 */
abstract class Database {

  /**
   * Flag to indicate a query call should simply return NULL.
1134
   *
1135
1136
   * This is used for queries that have no reasonable return value anyway, such
   * as INSERT statements to a table without a serial primary key.
1137
1138
   */
  const RETURN_NULL = 0;
1139

1140
1141
1142
1143
1144
1145
1146
1147
1148
  /**
   * Flag to indicate a query call should return the prepared statement.
   */
  const RETURN_STATEMENT = 1;

  /**
   * Flag to indicate a query call should return the number of affected rows.
   */
  const RETURN_AFFECTED = 2;
1149

1150
1151
1152
1153
  /**
   * Flag to indicate a query call should return the "last insert id".
   */
  const RETURN_INSERT_ID = 3;
Dries's avatar