database.inc 76.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// $Id$

/**
 * @file
 * Base classes for the database layer.
 */

/**
 * @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
15
 * the ability to support multiple database servers easily. The intent of
16
17
 * 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
18
 * a unified way. It also provides a structured interface for dynamically
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 * 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
 * db_query_range(). Module authors should also consider using pager_query() for
 * queries that return results that need to be presented on multiple pages, and
 * tablesort_sql() for generating appropriate queries for sortable tables.
 *
 * 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
 *   SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;
 * @endcode
 * one would instead call the Drupal functions:
 * @code
 *   $result = db_query_range('SELECT n.nid, n.title, n.created
 *     FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid), 0, 10);
 *   foreach($result as $record) {
 *     // Perform operations on $node->title, etc. here.
 *   }
 * @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.
 *
50
 *
51
 * All queries are passed as a prepared statement string. A
52
 * prepared statement is a "template" of a query that omits literal or variable
53
 * values in favor of placeholders. The values to place into those
54
 * placeholders are passed separately, and the database driver handles
55
 * inserting the values into the query in a secure fashion. That means you
56
 * should never quote or string-escape a value to be inserted into the query.
57
 *
58
 * There are two formats for placeholders: named and unnamed. Named placeholders
59
 * are strongly preferred in all cases as they are more flexible and
60
 * self-documenting.
61
 *
62
63
64
65
 * Named placeholders begin with a colon followed by a unique string. Example:
 * @code
 * SELECT nid, title FROM {node} WHERE uid=:uid
 * @endcode
66
 *
67
 * ":uid" is a placeholder that will be replaced with a literal value when
68
69
 * 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
70
71
 * 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
72
 * corresponding value to use. The array may be in any order.
73
 *
74
 * Unnamed placeholders are simply a question mark. Example:
75
76
77
 * @code
 * SELECT nid, title FROM {node} WHERE uid=?
 * @endcode
78
 *
79
 * In this case, the array of arguments must be an indexed array of values to
80
81
 * use in the exact same order as the placeholders in the query.
 *
82
 * Note that placeholders should be a "complete" value. For example, when
83
 * running a LIKE query the SQL wildcard character, %, should be part of the
84
 * value, not the query itself. Thus, the following is incorrect:
85
 *
86
87
88
 * @code
 * SELECT nid, title FROM {node} WHERE title LIKE :title%
 * @endcode
89
 *
90
 * It should instead read:
91
 *
92
93
94
 * @code
 * SELECT nid, title FROM {node} WHERE title LIKE :title
 * @endcode
95
 *
96
97
 * 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
98
 * into the query as one big string but as an explicitly separate value, the
99
 * database server knows where the query ends and a value begins. That is
100
 * considerably more secure against SQL injection than trying to remember
101
 * which values need quotation marks and string escaping and which don't.
102
 *
103
104
 *
 * INSERT, UPDATE, and DELETE queries need special care in order to behave
105
106
 * consistently across all different databases. Therefore, they use a special
 * object-oriented API for defining a query structurally. For example, rather than
107
108
109
110
111
112
113
114
115
 * @code
 * INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body')
 * @endcode
 * one would instead write:
 * @code
 * $fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
 * db_insert('my_table')->fields($fields)->execute();
 * @endcode
 * This method allows databases that need special data type handling to do so,
116
 * while also allowing optimizations such as multi-insert queries. UPDATE and
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
 * DELETE queries have a similar pattern.
 */


/**
 * Base Database API class.
 *
 * 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.
 *
 * @link http://us.php.net/manual/en/ref.pdo.php
 */
abstract class DatabaseConnection extends PDO {

  /**
   * Reference to the last statement that was executed.
   *
   * We only need this for the legacy db_affected_rows() call, which will be removed.
   *
137
   * @var DatabaseStatementInterface
138
139
140
141
   * @todo Remove this variable.
   */
  public $lastStatement;

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
  /**
   * 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;

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
  /**
   * Cache of prepared statements.
   *
   * This cache only lasts as long as the current page request, so it's not
   * as useful as it could be, but every little bit helps.
   *
   * @var Array
   */
  protected $preparedStatements = array();

  /**
   * The name of the Select class for this connection.
   *
   * Normally this and the following class names would be static variables,
   * but statics in methods are still global and shared by all instances.
   *
   * @var string
   */
  protected $selectClass = NULL;

  /**
   * The name of the Delete class for this connection.
   *
   * @var string
   */
  protected $deleteClass = NULL;

  /**
   * The name of the Insert class for this connection.
   *
   * @var string
   */
  protected $insertClass = NULL;

  /**
   * The name of the Merge class for this connection.
   *
   * @var string
   */
  protected $mergeClass = NULL;

  /**
   * The name of the Update class for this connection.
   *
   * @var string
   */
  protected $updateClass = NULL;

  /**
   * The name of the Transaction class for this connection.
   *
   * @var string
   */
  protected $transactionClass = NULL;

213
214
215
216
217
  /**
   * The name of the Statement class for this connection.
   *
   * @var string
   */
218
219
220
221
222
223
224
225
  protected $statementClass = 'DatabaseStatementBase';

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

227
228
229
230
231
232
233
  /**
   * The schema object for this connection.
   *
   * @var object
   */
  protected $schema = NULL;

234
  function __construct($dsn, $username, $password, $driver_options = array()) {
235
236
    // Because the other methods don't seem to work right.
    $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
237

238
    // Call PDO::__construct and PDO::setAttribute.
239
    parent::__construct($dsn, $username, $password, $driver_options);
240
241

    // Set a specific PDOStatement class if the driver requires that.
242
    if (!empty($this->statementClass)) {
243
      $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($this->statementClass, array($this)));
244
    }
245
246
247
248
249
  }

  /**
   * Return the default query options for any given query.
   *
250
   * A given query can be customized with a number of option flags in an
251
252
   * associative array.
   *
253
254
255
   *   target - The database "target" against which to execute a query. Valid
   *   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
256
257
   *   is not available, it will silently fall back to the "default" target.
   *   If multiple databases connections are specified with the same target,
258
   *   one will be selected at random for the duration of the request.
259
   *
260
261
   *   fetch - This element controls how rows from a result set will be returned.
   *   legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH, PDO::FETCH_OBJ,
262
   *   PDO::FETCH_NUM, or a string representing the name of a class. If a string
263
   *   is specified, each record will be fetched into a new object of that class.
264
   *   The behavior of all other values is defined by PDO. See
265
   *   http://www.php.net/PDOStatement-fetch
266
   *
267
   *   return - Depending on the type of query, different return values may be
268
269
   *   meaningful. This directive instructs the system which type of return
   *   value is desired. The system will generally set the correct value
270
   *   automatically, so it is extremely rare that a module developer will ever
271
272
   *   need to specify this value. Setting it incorrectly will likely lead to
   *   unpredictable results or fatal errors. Legal values include:
273
   *
274
   *     Database::RETURN_STATEMENT - Return the prepared statement object for the
275
   *     query. This is usually only meaningful for SELECT queries, where the
276
   *     statement object is how one accesses the result set returned by the query.
277
278
   *
   *     Database::RETURN_AFFECTED - Return the number of rows affected by an
279
   *     UPDATE or DELETE query. Be aware that means the number of rows
280
   *     actually changed, not the number of rows matched by the WHERE clause.
281
   *
282
283
   *     Database::RETURN_INSERT_ID - Return the sequence ID (primary key)
   *     created by an INSERT statement on a table that contains a serial column.
284
   *
285
   *     Database::RETURN_NULL - Do not return anything, as there is no
286
   *     meaningful value to return. That is the case for INSERT queries on
287
288
   *     tables that do not contain a serial column.
   *
289
290
   *   throw_exception - By default, the database system will catch any errors
   *   on a query as an Exception, log it, and then rethrow it so that code
291
   *   further up the call chain can take an appropriate action. To supress
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
   *   that behavior and simply return NULL on failure, set this option to FALSE.
   *
   * @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,
    );
  }

  /**
   * Append a database prefix to all tables in a query.
   *
   * 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
311
   * tables, allowing Drupal to coexist with other systems in the same database
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
   * if necessary.
   *
   * @param $sql
   *   A string containing a partial or entire SQL query.
   * @return
   *   The properly-prefixed string.
   */
  protected function prefixTables($sql) {
    global $db_prefix;

    if (is_array($db_prefix)) {
      if (array_key_exists('default', $db_prefix)) {
        $tmp = $db_prefix;
        unset($tmp['default']);
        foreach ($tmp as $key => $val) {
          $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
        }
        return strtr($sql, array('{' => $db_prefix['default'] , '}' => ''));
      }
      else {
        foreach ($db_prefix as $key => $val) {
          $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
        }
        return strtr($sql, array('{' => '' , '}' => ''));
      }
    }
    else {
      return strtr($sql, array('{' => $db_prefix , '}' => ''));
    }
  }

  /**
   * Prepare a query string and return the prepared statement.
345
   *
346
   * This method caches prepared statements, reusing them when
347
   * possible. It also prefixes tables names enclosed in curly-braces.
348
349
350
351
352
353
354
355
356
   *
   * @param $query
   *   The query string as SQL, with curly-braces surrounding the
   *   table names.
   * @return
   *   A PDO prepared statement ready for its execute() method.
   */
  protected function prepareQuery($query) {
    $query = self::prefixTables($query);
357
    if (empty($this->preparedStatements[$query])) {
358
      // Call PDO::prepare.
359
      $this->preparedStatements[$query] = parent::prepare($query);
360
    }
361
    return $this->preparedStatements[$query];
362
363
  }

364
365
366
  /**
   * Tell this connection object what its target value is.
   *
367
   * This is needed for logging and auditing. It's sloppy to do in the
368
   * constructor because the constructor for child classes has a different
369
   * signature. We therefore also ensure that this function is only ever
370
371
372
   * called once.
   *
   * @param $target
373
   *   The target this connection is for. Set to NULL (default) to disable
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
   *   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;
  }

  /**
   * Associate a logging object with this connection.
   *
   * @param $logger
   *   The logging object we want to use.
   */
  public function setLogger(DatabaseLog $logger) {
    $this->logger = $logger;
  }

  /**
   * Get the current logging object for this connection.
   *
   * @return
406
   *   The current logging object for this connection. If there isn't one,
407
408
409
410
411
412
   *   NULL is returned.
   */
  public function getLogger() {
    return $this->logger;
  }

413
414
  /**
   * Create the appropriate sequence name for a given table and serial field.
415
   *
416
   * This information is exposed to all database drivers, although it is only
417
   * useful on some of them. This method is table prefix-aware.
418
   *
419
420
421
422
423
424
425
426
427
428
   * @param $table
   *   The table name to use for the sequence.
   * @param $field
   *   The field name to use for the sequence.
   * @return
   *   A table prefix-parsed string for the sequence name.
   */
  public function makeSequenceName($table, $field) {
    return $this->prefixTables('{'. $table .'}_'. $field .'_seq');
  }
429

430
431
432
433
  /**
   * Executes a query string against the database.
   *
   * This method provides a central handler for the actual execution
434
   * of every query. All queries executed by Drupal are executed as
435
   * PDO prepared statements.
436
   *
437
   * @param $query
438
439
   *   The query to execute. In most cases this will be a string containing
   *   an SQL query with placeholders. An already-prepared instance of
440
   *   DatabaseStatementInterface may also be passed in order to allow calling code
441
   *   to manually bind variables to a query. If a DatabaseStatementInterface
442
   *   is passed, the $args array will be ignored.
443
444
   *
   *   It is extremely rare that module code will need to pass a statement
445
   *   object to this method. It is used primarily for database drivers for
446
447
   *   databases that require special LOB field handling.
   * @param $args
448
   *   An array of arguments for the prepared statement. If the prepared
449
450
451
   *   statement uses ? placeholders, this array must be an indexed array.
   *   If it contains named placeholders, it must be an associative array.
   * @param $options
452
   *   An associative array of options to control how the query is run. See
453
454
455
456
457
458
   *   the documentation for DatabaseConnection::defaultOptions() for details.
   * @return
   *   This method will return one of: The executed statement, the number of
   *   rows affected by the query (not the number matched), or the generated
   *   insert id 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
459
   *   not be set by a user. If there is an error, this method will return NULL
460
461
   *   and may throw an exception if $options['throw_exception'] is TRUE.
   */
462
  public function query($query, array $args = array(), $options = array()) {
463
464
465

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

467
468
    try {
      // We allow either a pre-bound statement object or a literal string.
469
470
      // In either case, we want to end up with an executed statement object,
      // which we pass to PDOStatement::execute.
471
      if ($query instanceof DatabaseStatementInterface) {
472
473
474
475
476
477
478
        $stmt = $query;
        $stmt->execute(NULL, $options);
      }
      else {
        $stmt = $this->prepareQuery($query);
        $stmt->execute($args, $options);
      }
479

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
      // Depending on the type of query we may need to return a different value.
      // See DatabaseConnection::defaultOptions() for a description of each value.
      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) {
496
      _db_check_install_needed();
497
      if ($options['throw_exception']) {
498
499
        if ($query instanceof DatabaseStatementInterface) {
          $query_string = $stmt->getQueryString();
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
        }
        else {
          $query_string = $query;
        }
        throw new PDOException($query_string . " - \n" . print_r($args,1) . $e->getMessage());
      }
      return NULL;
    }
  }

  /**
   * Prepare and return a SELECT query object with the specified ID.
   *
   * @see SelectQuery
   * @param $table
   *   The base table for this query, that is, the first table in the FROM
516
   *   clause. This table will also be used as the "base" table for query_alter
517
518
519
520
521
522
523
524
   *   hook implementations.
   * @param $alias
   *   The alias of the base table of this query.
   * @param $options
   *   An array of options on the query.
   * @return
   *   A new SelectQuery object.
   */
525
  public function select($table, $alias = NULL, array $options = array()) {
526
527
528
529
    if (empty($this->selectClass)) {
      $this->selectClass = 'SelectQuery_' . $this->driver();
      if (!class_exists($this->selectClass)) {
        $this->selectClass = 'SelectQuery';
530
531
      }
    }
532
533
534
535
536
537
    $class = $this->selectClass;
    // new is documented as the highest precedence operator so this will
    // create a class named $class and pass the arguments into the constructor,
    // instead of calling a function named $class with the arguments listed and
    // then creating using the return value as the class name.
    return new $class($table, $alias, $this, $options);
538
539
540
541
542
543
544
545
546
547
548
  }

  /**
   * Prepare and return an INSERT query object with the specified ID.
   *
   * @see InsertQuery
   * @param $options
   *   An array of options on the query.
   * @return
   *   A new InsertQuery object.
   */
549
  public function insert($table, array $options = array()) {
550
551
552
553
    if (empty($this->insertClass)) {
      $this->insertClass = 'InsertQuery_' . $this->driver();
      if (!class_exists($this->insertClass)) {
        $this->insertClass = 'InsertQuery';
554
555
      }
    }
556
557
    $class = $this->insertClass;
    return new $class($this, $table, $options);
558
559
560
561
562
563
564
565
566
567
568
  }

  /**
   * Prepare and return a MERGE query object with the specified ID.
   *
   * @see MergeQuery
   * @param $options
   *   An array of options on the query.
   * @return
   *   A new MergeQuery object.
   */
569
  public function merge($table, array $options = array()) {
570
571
572
573
    if (empty($this->mergeClass)) {
      $this->mergeClass = 'MergeQuery_' . $this->driver();
      if (!class_exists($this->mergeClass)) {
        $this->mergeClass = 'MergeQuery';
574
575
      }
    }
576
577
    $class = $this->mergeClass;
    return new $class($this, $table, $options);
578
579
  }

580

581
582
583
584
585
586
587
588
589
  /**
   * Prepare and return an UPDATE query object with the specified ID.
   *
   * @see UpdateQuery
   * @param $options
   *   An array of options on the query.
   * @return
   *   A new UpdateQuery object.
   */
590
  public function update($table, array $options = array()) {
591
592
593
594
    if (empty($this->updateClass)) {
      $this->updateClass = 'UpdateQuery_' . $this->driver();
      if (!class_exists($this->updateClass)) {
        $this->updateClass = 'UpdateQuery';
595
596
      }
    }
597
598
    $class = $this->updateClass;
    return new $class($this, $table, $options);
599
600
601
602
603
604
605
606
607
608
609
  }

  /**
   * Prepare and return a DELETE query object with the specified ID.
   *
   * @see DeleteQuery
   * @param $options
   *   An array of options on the query.
   * @return
   *   A new DeleteQuery object.
   */
610
  public function delete($table, array $options = array()) {
611
612
613
614
    if (empty($this->deleteClass)) {
      $this->deleteClass = 'DeleteQuery_' . $this->driver();
      if (!class_exists($this->deleteClass)) {
        $this->deleteClass = 'DeleteQuery';
615
616
      }
    }
617
618
    $class = $this->deleteClass;
    return new $class($this, $table, $options);
619
620
621
622
623
624
625
626
627
628
629
  }

  /**
   * Returns a DatabaseSchema object for manipulating the schema of this database.
   *
   * This method will lazy-load the appropriate schema library file.
   *
   * @return
   *   The DatabaseSchema object for this connection.
   */
  public function schema() {
630
    if (empty($this->schema)) {
631
      $class_type = 'DatabaseSchema_' . $this->driver();
632
      $this->schema = new $class_type($this);
633
    }
634
    return $this->schema;
635
636
637
638
639
640
641
642
643
644
645
646
647
  }

  /**
   * 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) {
648
    return preg_replace('/[^A-Za-z0-9_]+/', '', $table);
649
650
651
652
653
654
655
  }

  /**
   * Returns a new DatabaseTransaction object on this connection.
   *
   * @param $required
   *   If executing an operation that absolutely must use transactions, specify
656
   *   TRUE for this parameter. If the connection does not support transactions,
657
658
659
660
661
662
663
   *   this method will throw an exception and the operation will not be possible.
   * @see DatabaseTransaction
   */
  public function startTransaction($required = FALSE) {
    if ($required && !$this->supportsTransactions()) {
      throw new TransactionsNotSupportedException();
    }
664

665
666
667
668
    if (empty($this->transactionClass)) {
      $this->transactionClass = 'DatabaseTransaction_' . $this->driver();
      if (!class_exists($this->transactionClass)) {
        $this->transactionClass = 'DatabaseTransaction';
669
670
      }
    }
671
    return new $this->transactionClass($this);
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
  }

  /**
   * 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
   * 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.
   *
   * @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.
   * @return
   *   A database query result resource, or NULL if the query was not executed
   *   correctly.
   */
696
  abstract public function queryRange($query, array $args, $from, $count, array $options = array());
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716

  /**
   * 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
   * 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.
   *
   * 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.
   * @param $tablename
   *   The name of the temporary table to select into. This name will not be
   *   prefixed as there is no risk of collision.
717
   * @param $options
718
   *   An associative array of options to control how the query is run. See
719
   *   the documentation for DatabaseConnection::defaultOptions() for details.
720
721
722
723
   * @return
   *   A database query result resource, or FALSE if the query was not executed
   *   correctly.
   */
724
  abstract function queryTemporary($query, array $args, $tablename, array $options = array());
725
726
727
728
729
730
731
732
733
734
735
736
737
738

  /**
   * Returns the type of database driver.
   *
   * 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().
   */
  abstract public function driver();

  /**
   * Determine if this driver supports transactions.
   */
739
740
741
  public function supportsTransactions() {
   return $this->transactionSupport;
  }
742
743
744
745
746
747

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

748

749
750
751
752
  /**
   * Gets any special processing requirements for the condition operator.
   *
   * Some condition types require special processing, such as IN, because
753
754
   * the value data they pass in is not a simple value. This is a simple
   * overridable lookup function. Database connections should define only
755
756
757
758
   * those operators they wish to be handled differently than the default.
   *
   * @see DatabaseCondition::compile().
   * @param $operator
759
   *   The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
760
761
762
763
764
765
766
767
768
   * @return
   *   The extra handling directives for the specified operator, or NULL.
   */
  abstract public function mapConditionOperator($operator);
}

/**
 * Primary front-controller for the database system.
 *
769
 * This class is uninstantiatable and un-extendable. It acts to encapsulate
770
771
772
773
774
775
776
777
 * 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.
778
   *
779
780
781
782
783
   * This is used for queries that have no reasonable return value
   * anyway, such as INSERT statements to a table without a serial
   * primary key.
   */
  const RETURN_NULL = 0;
784

785
786
787
788
789
790
791
792
793
  /**
   * 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;
794

795
796
797
798
  /**
   * Flag to indicate a query call should return the "last insert id".
   */
  const RETURN_INSERT_ID = 3;
799

800
  /**
801
   * An nested array of all active connections. It is keyed by database name and target.
802
803
804
805
806
807
808
809
810
811
812
813
   *
   * @var array
   */
  static protected $connections = array();

  /**
   * A processed copy of the database connection information from settings.php
   *
   * @var array
   */
  static protected $databaseInfo = NULL;

814
815
816
817
818
819
820
  /**
   * A list of key/target credentials to simply ignore.
   *
   * @var array
   */
  static protected $ignoreTargets = array();

821
822
823
824
825
826
827
  /**
   * The key of the currently active database connection.
   *
   * @var string
   */
  static protected $activeKey = 'default';

828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
  /**
   * An array of active query log objects.
   *
   * Every connection has one and only one logger object for all targets
   * and logging keys.
   *
   * array(
   *   '$db_key' => DatabaseLog object.
   * );
   *
   * @var array
   */
  static protected $logs = array();

  /**
   * Start logging a given logging key on the specified connection.
   *
   * @see DatabaseLog
   * @param $logging_key
   *   The logging key to log.
   * @param $key
   *   The database connection key for which we want to log.
   * @return
851
   *   The query log object. Note that the log object does support richer
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
   *   methods than the few exposed through the Database class, so in some
   *   cases it may be desirable to access it directly.
   */
  final public static function startLog($logging_key, $key = 'default') {
    if (empty(self::$logs[$key])) {
      self::$logs[$key] = new DatabaseLog($key);

      // Every target already active for this connection key needs to have
      // the logging object associated with it.
      if (!empty(self::$connections[$key])) {
        foreach (self::$connections[$key] as $connection) {
          $connection->setLogger(self::$logs[$key]);
        }
      }
    }

    self::$logs[$key]->start($logging_key);
    return self::$logs[$key];
  }

  /**
   * Retrieve the queries logged on for given logging key.
   *
875
   * This method also ends logging for the specified key. To get the query log
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
   * to date without ending the logger request the logging object by starting
   * it again (which does nothing to an open log key) and call methods on it as
   * desired.
   *
   * @see DatabaseLog
   * @param $logging_key
   *   The logging key to log.
   * @param $key
   *   The database connection key for which we want to log.
   * @return
   *   The query log for the specified logging key and connection.
   */
  final public static function getLog($logging_key, $key = 'default') {
    if (empty(self::$logs[$key])) {
      return NULL;
    }
    $queries = self::$logs[$key]->get($logging_key);
    self::$logs[$key]->end($logging_key);
    return $queries;
  }

897
898
899
900
901
902
903
904
905
  /**
   * Gets the active connection object for the specified target.
   *
   * @return
   *   The active connection object.
   */
  final public static function getActiveConnection($target = 'default') {
    // This could just be a call to getConnection(), but that's an extra
    // method call for every single query.
906
907
908
909
910
911

    // If the requested target does not exist, or if it is ignored, we fall back
    // to the default target. The target is typically either "default" or "slave",
    // indicating to use a slave SQL server if one is available. If it's not
    // available, then the default/master server is the correct server to use.
    if (!empty(self::$ignoreTargets[self::$activeKey][$target]) || !isset(self::$databaseInfo[self::$activeKey][$target])) {
912
913
914
      $target = 'default';
    }

915
    if (!isset(self::$connections[self::$activeKey][$target])) {
916
      self::openConnection(self::$activeKey, $target);
917
918
919
920
921
922
923
924
925
926
927
928
    }

    return isset(self::$connections[self::$activeKey][$target]) ? self::$connections[self::$activeKey][$target] : NULL;
  }

  /**
   * Gets the connection object for the specified database key and target.
   *
   * @return
   *   The corresponding connection object.
   */
  final public static function getConnection($key = 'default', $target = 'default') {
929
930
931
932
933
    // If the requested target does not exist, or if it is ignored, we fall back
    // to the default target. The target is typically either "default" or "slave",
    // indicating to use a slave SQL server if one is available. If it's not
    // available, then the default/master server is the correct server to use.
    if (!empty(self::$ignoreTargets[$key][$target]) || !isset(self::$databaseInfo[$key][$target])) {
934
935
936
      $target = 'default';
    }

937
    if (!isset(self::$connections[$key][$target])) {
938
      self::openConnection($key, $target);
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
    }

    return isset(self::$connections[$key][$target]) ? self::$connections[$key][$target] : NULL;
  }

  /**
   * Determine if there is an active connection.
   *
   * Note that this method will return FALSE if no connection has been established
   * yet, even if one could be.
   *
   * @return
   *   TRUE if there is at least one database connection established, FALSE otherwise.
   */
  final public static function isActiveConnection() {
954
    return !empty(self::$activeKey) && !empty(self::$connections) && !empty(self::$connections[self::$activeKey]);
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
  }

  /**
   * Set the active connection to the specified key.
   *
   * @return
   *   The previous database connection key.
   */
  final public static function setActiveConnection($key = 'default') {
    if (empty(self::$databaseInfo)) {
      self::parseConnectionInfo();
    }

    if (!empty(self::$databaseInfo[$key])) {
      $old_key = self::$activeKey;
      self::$activeKey = $key;
      return $old_key;
    }
  }

  /**
   * Process the configuration file for database information.
   */
  final protected static function parseConnectionInfo() {
    global $databases;

981
    _db_check_install_needed();
982

983
    $databaseInfo = $databases;
984
985
    foreach ($databaseInfo as $index => $info) {
      foreach ($databaseInfo[$index] as $target => $value) {
986
        // If there is no "driver" property, then we assume it's an array of
987
        // possible connections for this target. Pick one at random. That
988
989
990
991
992
993
994
995
996
        // allows us to have, for example, multiple slave servers.
        if (empty($value['driver'])) {
          $databaseInfo[$index][$target] = $databaseInfo[$index][$target][mt_rand(0, count($databaseInfo[$index][$target]) - 1)];
        }
      }
    }

    self::$databaseInfo = $databaseInfo;
  }
997

998
999
1000
1001
1002
  /**
   * Add database connection info for a given key/target.
   *
   * This method allows the addition of new connection credentials at runtime.
   * Under normal circumstances the preferred way to specify database credentials
1003
   * is via settings.php. However, this method allows them to be added at
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
   * arbitrary times, such as during unit tests, when connecting to admin-defined
   * third party databases, etc.
   *
   * If the given key/target pair already exists, this method will be ignored.
   *
   * @param $key
   *   The database key.
   * @param $target
   *   The database target name.
   * @param $info
   *   The database connection information, as it would be defined in settings.php.
   *   Note that the structure of this array will depend on the database driver
   *   it is connecting to.
   */
  public static function addConnectionInfo($key, $target, $info) {
    if (empty(self::$databaseInfo[$key][$target])) {
      self::$databaseInfo[$key][$target] = $info;
    }
  }

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
  /**
   * Gets information on the specified database connection.
   *
   * @param $connection
   *   The connection key for which we want information.
   */
  final public static function getConnectionInfo($key = 'default') {
    if (empty(self::$databaseInfo)) {
      self::parseConnectionInfo();
    }

    if (!empty(self::$databaseInfo[$key])) {
      return self::$databaseInfo[$key];
    }
1038

1039
1040
1041
1042
1043
1044
  }

  /**
   * Open a connection to the server specified by the given key and target.
   *
   * @param $key
1045
   *   The database connection key, as specified in settings.php. The default
1046
1047
   *   is "default".
   * @param $target
1048
   *   The database target to open.
1049
1050
1051
1052
   */
  final protected static function openConnection($key, $target) {
    global $db_prefix;

1053
    if (empty(self::$databaseInfo)) {
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
      self::parseConnectionInfo();
    }
    try {
      // If the requested database does not exist then it is an unrecoverable error.
      if (!isset(self::$databaseInfo[$key])) {
        throw new Exception('DB does not exist');
      }

      if (!$driver = self::$databaseInfo[$key][$target]['driver']) {
        throw new Exception('Drupal is not set up');
      }
1065

1066
1067
1068
      // We cannot rely on the registry yet, because the registry requires
      // an open database connection.
      $driver_class = 'DatabaseConnection_' . $driver;
1069
      require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
1070
      self::$connections[$key][$target] = new $driver_class(self::$databaseInfo[$key][$target]);
1071
1072
1073
1074
1075
1076
1077
      self::$connections[$key][$target]->setTarget($target);

      // If we have any active logging objects for this connection key, we need
      // to associate them with the connection we just opened.
      if (!empty(self::$logs[$key])) {
        self::$connections[$key][$target]->setLogger(self::$logs[$key]);
      }
1078
1079
1080
1081

      // We need to pass around the simpletest database prefix in the request
      // and we put that in the user_agent header.
      if (preg_match("/^simpletest\d+$/", $_SERVER['HTTP_USER_AGENT'])) {
1082
        $db_prefix .= $_SERVER['HTTP_USER_AGENT'];
1083
1084
1085
1086
      }
    }
    catch (Exception $e) {
      // It is extremely rare that an exception will be generated here other
1087
      // than when installing. We therefore intercept it and try the installer,
1088
      // passing on the exception otherwise.
1089
      _db_check_install_needed();
1090
1091
1092
      throw $e;
    }
  }
1093
1094
1095
1096

  /**
   * Instruct the system to temporarily ignore a given key/target.
   *
1097
   * At times we need to temporarily disable slave queries. To do so,
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
   * call this method with the database key and the target to disable.
   * That database key will then always fall back to 'default' for that
   * key, even if it's defined.
   *
   * @param $key
   *   The database connection key.
   * @param $target
   *   The target of the specified key to ignore.
   */
  public static function ignoreTarget($key, $target) {
    self::$ignoreTargets[$key][$target] = TRUE;
  }

1111
1112
1113
1114
}

/**
 * Exception to mark databases that do not support transations.
1115
1116
 *
 * This exception will be thrown when a transaction is started that does not
1117
 * allow for the "silent fallback" of no transaction and the database connection
1118
 * in use does not support transactions. The calling code must then take
1119
1120
1121
1122
1123
1124
1125
 * appropriate action.
 */
class TransactionsNotSupportedException extends PDOException { }

/**
 * A wrapper class for creating and managing database transactions.
 *
1126
1127
 * Not all databases or database configurations support transactions. For
 * example, MySQL MyISAM tables do not. It is also easy to begin a transaction
1128
1129
1130
 * and then forget to commit it, which can lead to connection errors when
 * another transaction is started.
 *
1131
1132
1133
1134
1135
 * This class acts as a wrapper for transactions. To begin a transaction,
 * simply instantiate it. When the object goes out of scope and is destroyed
 * it will automatically commit. It also will check to see if the specified
 * connection supports transactions. If not, it will simply skip any transaction
 * commands, allowing user-space code to proceed normally. The only difference
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
 * is that rollbacks won't actually do anything.
 *
 * In the vast majority of cases, you should not instantiate this class directly.
 * Instead, call ->startTransaction() from the appropriate connection object.
 */
class DatabaseTransaction {

  /**
   * The connection object for this transaction.
   *
   * @var DatabaseConnection
   */
  protected $connection;

  /**
   * Whether or not this connection supports transactions.
   *
   * This can be derived from the connection itself with a method call,
   * but is cached here for performance.
   *
   * @var boolean
   */
  protected $supportsTransactions;

  /**
   * Whether or not this transaction has been rolled back.
   *
   * @var boolean
   */
  protected $hasRolledBack = FALSE;

  /**
   * Whether or not this transaction has been committed.
   *
   * @var boolean
   */
  protected $hasCommitted = FALSE;

  /**
   * Track the number of "layers" of transactions currently active.
1176
   *
1177
   * On many databases transactions cannot nest. Instead, we track
1178
1179
1180
1181
1182
1183
   * nested calls to transactions and collapse them into a single
   * transaction.
   *
   * @var int
   */
  protected static $layers = 0;
1184

1185
1186
1187
1188
1189
1190
1191
  public function __construct(DatabaseConnection $connection) {
    $this->connection = $connection;
    $this->supportsTransactions = $connection->supportsTransactions();

    if (self::$layers == 0 && $this->supportsTransactions) {
      $connection->beginTransaction();
    }
1192

1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
    ++self::$layers;
  }

  /**
   * Commit this transaction.
   */
  public function commit() {
    --self::$layers;
    if (self::$layers == 0 && $this->supportsTransactions) {
      $this->connection->commit();
      $this->hasCommitted = TRUE;
    }
  }

  /**
   * Roll back this transaction.
   */
  public function rollBack() {
    if ($this->supportsTransactions) {
      $this->connection->rollBack();
      $this->hasRolledBack = TRUE;
    }
  }

  /**
   * Determine if this transaction has already been rolled back.
   *
   * @return
   *   TRUE if the transaction has been rolled back, FALSE otherwise.
   */
  public function hasRolledBack() {
    return $this->hasRolledBack;
  }

  public function __destruct() {
    --self::$layers;
    if (self::$layers == 0 && $this->supportsTransactions && !$this->hasRolledBack && !$this->hasCommitted) {
      $this->connection->commit();
    }
  }

}

/**
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
 * A prepared statement.
 *
 * Some methods in that class are purposely commented out. Due to a change in
 * how PHP defines PDOStatement, we can't define a signature for those methods that
 * will work the same way between versions older than 5.2.6 and later versions.
 *
 * Please refer to http://bugs.php.net/bug.php?id=42452 for more details.
 *
 * Child implementations should either extend PDOStatement:
 * @code
 * class DatabaseStatement_oracle extends PDOStatement implements DatabaseStatementInterface {}
 * @endcode
 *
 * or implement their own class, but in that case they will also have to implement
 * the Iterator or IteratorArray interfaces before DatabaseStatementInterface:
 * @code
 * class DatabaseStatement_oracle implements Iterator, DatabaseStatementInterface {}
 * @endcode
 */
interface DatabaseStatementInterface extends Traversable {

  /**
   * Executes a prepared statement
   *
   * @param $args
   *   An array of values with as many elements as there are bound parameters in the SQL statement being executed.
   * @param $options
   *   An array of options for this query.
   * @return
   *   TRUE on success, or FALSE on failure.
   */
  public function execute($args, $options);

  /**
   * Get the query string of that statement.
   *
   * @return
   *   The query string, in its form with placeholders.
   */
  public function getQueryString();

  /**
   * Returns the number of rows affected by the last SQL statement.
   *
   * @return
   *   The number of rows affected by the last DELETE, INSERT, or UPDATE
   *   statement executed
   */
  public function rowCount();

  /**
   * Set the default fetch mode for this statement.
   *
   * See http://php.net/manual/en/pdo.constants.php for the definition of the
   * constants used.
   *
   * @param $mode
   *   One of the PDO::FETCH_* constants.
   * @param $a1
   *   An option depending of the fetch mode specified by $mode:
   *    - for PDO::FETCH_COLUMN, it is the index of the column to fetch,
   *    - for PDO::FETCH_CLASS, it is the name of the class to create, and
   *    - for PDO::FETCH_INTO, it is the object to add the data to.
   * @param $a2
   *  In case of when mode is PDO::FETCH_CLASS, the optional arguments to
   *  pass to the constructor.
   */
  // public function setFetchMode($mode, $a1 = NULL, $a2 = array());

  /**
   * Fetches the next row from a result set.
   *
   * See http://php.net/manual/en/pdo.constants.php for the definition of the
   * constants used.
   *
   * @param $mode
   *   One of the PDO::FETCH_* constants.
   *   Default to what was specified by setFetchMode().
   * @param $cursor_orientation
   *   Not implemented in all database drivers, don't use.
   * @param $cursor_offset
   *   Not implemented in all database drivers, don't use.
   * @return
   *   A result, formatted according to $mode.
   */
  // public function fetch($mode = NULL, $cursor_orientation = NULL, $cursor_offset = NULL);

  /**
   * Return a single field out of the current
   *
   * @param $index
1328
   *   The numeric index of the field to return. Defaults to the first field.
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
   * @return
   *   A single field from the next record.
   */
  public function fetchField($index = 0);

  /**
   * Fetches the next row and returns it as an object.
   *
   * The object will be of the class specified by DatabaseStatementInterface::setFetchMode()
   * or stdClass if not specified.
   */
  // public function fetchObject();

  /**
   * Fetches the next row and returns it as an associative array.
   *
   * This method corresponds to PDOStatement::fetchObject(),
1346
   * but for associative arrays. For some reason PDOStatement does
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
   * not have a corresponding array helper method, so one is added.
   *
   * @return
   *   An associative array.
   */
  public function fetchAssoc();

  /**
   * Returns an array containing all of the result set rows.
   *
   * @param $mode
   *   One of the PDO::FETCH_* constants.
   * @param $column_index
   *   If $mode is PDO::FETCH_COLUMN, the index of the column to fetch.
   * @param $constructor_arguments
   *   If $mode is PDO::FETCH_CLASS, the arguments to pass to the constructor.
   * @return
   *   An array of results.
   */
1366
  // function fetchAll($mode = NULL, $column_index = NULL, array $constructor_arguments);
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409

  /**
   * Returns an entire single column of a result set as an indexed array.
   *
   * Note that this method will run the result set to the end.
   *
   * @param $index
   *   The index of the column number to fetch.
   * @return
   *   An indexed array.
   */
  public function fetchCol($index = 0);

  /**
   * Returns the entire result set as a single associative array.
   *
   * This method is only useful for two-column result sets. It will return
   * an associative array where the key is one column from the result set
   * and the value is another field. In most cases, the default of the first two
   * columns is appropriate.
   *
   * Note that this method will run the result set to the end.
   *
   * @param $key_index
   *   The numeric index of the field to use as the array key.
   * @param $value_index
   *   The numeric index of the field to use as the array value.
   * @return
   *   An associative array.
   */
  public function fetchAllKeyed($key_index = 0, $value_index = 1);

  /**
   * Returns an entire result set as an associative array keyed by the named field.
   *
   * If the given key appears multiple times, later records will overwrite
   * earlier ones.
   *
   * Note that this method will run the result set to the end.
   *
   * @param $key
   *   The name of the field on which to index the array.
   * @param $fetch
1410
   *   The fetchmode to use. If set to PDO::FETCH_ASSOC, PDO::FETCH_NUM, or
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
   *   PDO::FETCH_BOTH the returned value with be an array of arrays. For any
   *   other value it will be an array of objects.
   * @return
   *   An associative array.
   */
  public function fetchAllAssoc($key, $fetch = PDO::FETCH_OBJ);
}

/**
 * Default implementation of DatabaseStatementInterface.
1421
 *
1422
 * PDO allows us to extend the PDOStatement class to provide additional
1423
1424
 * functionality beyond that offered by default. We do need extra
 * functionality. By default, this class is not driver-specific. If a given
1425
1426
1427
1428
 * driver needs to set a custom statement class, it may do so in its constructor.
 *
 * @link http://us.php.net/pdostatement
 */
1429
class DatabaseStatementBase extends PDOStatement implements DatabaseStatementInterface {
1430
1431
1432

  /**
   * Reference to the database connection object for this statement.
1433
   *
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
   * The name $dbh is inherited from PDOStatement.
   *
   * @var DatabaseConnection
   */
  public $dbh;

  protected function __construct($dbh) {
    $this->dbh = $dbh;
    $this->setFetchMode(PDO::FETCH_OBJ);
  }

  public function execute($args, $options) {
    if (isset($options['fetch'])) {
      if (is_string($options['fetch'])) {
1448
1449
1450
1451
        // Default to an object. Note: db fields will be added to the object
        // before the constructor is run. If you need to assign fields after
        // the constructor is run, see http://drupal.org/node/315092.
        $this->setFetchMode(PDO::FETCH_CLASS, $options['fetch']);
1452
1453
1454
1455
1456
1457
      }
      else {
        $this->setFetchMode($options['fetch']);
      }
    }
    $this->dbh->lastStatement = $this;
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471

    $logger = $this->dbh->getLogger();
    if (!empty($logger)) {
      $query_start = microtime(TRUE);
    }

    $return = parent::execute($args);

    if (!empty($logger)) {
      $query_end = microtime(TRUE);
      $logger->log($this, $args, $query_end - $query_start);
    }

    return $return;
1472
1473
  }

1474
1475
1476
1477
  public function getQueryString() {
    return $this->queryString;
  }

1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
  public function fetchCol($index = 0) {
    return $this->fetchAll(PDO::FETCH_COLUMN, $index);
  }

  public function fetchAllAssoc($key, $fetch = PDO::FETCH_OBJ) {
    $return = array();
    $this->setFetchMode($fetch);
    if (in_array($fetch, array(PDO::FETCH_ASSOC, PDO::FETCH_NUM, PDO::FETCH_BOTH))) {
      foreach ($this as $record) {
        $return[$record[$key]] = $record;
      }
    }
    else {
      foreach ($this as $record) {
        $return[$record->$key] = $record;
      }
    }
    return $return;
  }

  public function fetchAllKeyed($key_index = 0, $value_index = 1) {
    $return = array();
    $this->setFetchMode(PDO::FETCH_NUM);
    foreach ($this as $record) {
      $return[$record[$key_index]] = $record[$value_index];
    }
    return $return;
  }

  public function fetchField($index = 0) {
1508
    // Call PDOStatement::fetchColumn to fetch the field.
1509
1510
1511
1512
    return $this->fetchColumn($index);
  }

  public function fetchAssoc() {
1513
    // Call PDOStatement::fetch to fetch the row.
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
    return $this->fetch(PDO::FETCH_ASSOC);
  }
}

/**
 * The following utility functions are simply convenience wrappers.
 * They should never, ever have any database-specific code in them.
 */

/**
 * Execute an arbitrary query string against the active database.
 *
1526
1527
 * Do not use this function for INSERT, UPDATE, or DELETE queries. Those should
 * be handled via the appropriate query builder factory. Use this function for
1528
1529
1530
1531
 * SELECT queries that do not require a query builder.
 *
 * @see DatabaseConnection::defaultOptions()
 * @param $query
1532
 *   The prepared statement query to run. Although it will accept both
1533
1534
1535
 *   named and unnamed placeholders, named placeholders are strongly preferred
 *   as they are more self-documenting.
 * @param $args
1536
1537
 *   An array of values to substitute into the query. If the query uses named
 *   placeholders, this is an associative array in any order. If the query uses
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
 *   unnamed placeholders (?), this is an indexed array and the order must match
 *   the order of placeholders in the query string.
 * @param $options
 *   An array of options to control how the query operates.
 * @return
 *   A prepared statement object, already executed.
 */
function db_query($query, $args = array(), $options = array()) {
  if (!is_array($args)) {
    $args = func_get_args();
    array_shift($args);
  }
  list($query, $args, $options) = _db_query_process_args($query, $args, $options);
1551

1552
1553
1554
1555
1556
1557
1558
1559
  return Database::getActiveConnection($options['target'])->query($query, $args, $options);
}

/**
 * Execute an arbitrary query string against the active database, restricted to a specified range.
 *
 * @see DatabaseConnection::defaultOptions()
 * @param $query
1560
 *   The prepared statement query to run. Although it will accept both
1561
1562
1563
 *   named and unnamed placeholders, named placeholders are strongly preferred
 *   as they are more self-documenting.
 * @param $args
1564
1565
 *   An array of values to substitute into the query. If the query uses named
 *   placeholders, this is an associative array in any order. If the query uses
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
 *   unnamed placeholders (?), this is an indexed array and the order must match
 *   the order of placeholders in the query string.
 * @param $from
 *   The first record from the result set to return.
 * @param $limit
 *   The number of records to return from the result set.
 * @param $options
 *   An array of options to control how the query operates.
 * @return
 *   A prepared statement object, already executed.
 */
function db_query_range($query, $args, $from = 0, $count = 0, $options = array()) {
  if (!is_array($args)) {
    $args = func_get_args();
    array_shift($args);
    $count = array_pop($args);
    $from = array_pop($args);
  }
  list($query, $args, $options) = _db_query_process_args($query, $args, $options);
1585

1586
1587
1588
1589
1590
1591
1592
1593
  return Database::getActiveConnection($options['target'])->queryRange($query, $args, $from, $count, $options);
}

/**
 * Execute a query string against the active database and save the result set to a temp table.
 *
 * @see DatabaseConnection::defaultOptions()
 * @param $query
1594
 *   The prepared statement query to run. Although it will accept both
1595
1596
1597
 *   named and unnamed placeholders, named placeholders are strongly preferred
 *   as they are more self-documenting.
 * @param $args
1598
1599
 *   An array of values to substitute into the query. If the query uses named
 *   placeholders, this is an associative array in any order. If the query uses
1600
1601
 *   unnamed placeholders (?), this is an indexed array and the order must match
 *   the order of placeholders in the query string.
1602
1603
1604
 * @param $tablename
 *   The name of the temporary table to select into. This name will not be
 *   prefixed as there is no risk of collision.
1605
1606
1607
1608
1609
1610
1611
1612
1613
 * @param $options
 *   An array of options to control how the query operates.
 */
function db_query_temporary($query, $args, $tablename, $options = array()) {
  if (!is_array($args)) {
    $args = func_get_args();
    array_shift($args);
  }
  list($query, $args, $options) = _db_query_process_args($query, $args, $options);
1614

1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
  return Database::getActiveConnection($options['target'])->queryTemporary($query, $args, $tablename, $options);
}

/**
 * Returns a new InsertQuery object for the active database.
 *
 * @param $table
 *   The table into which to insert.
 * @param $options
 *   An array of options to control how the query operates.
 * @return
 *   A new InsertQuery object for this connection.
 */
1628
function db_insert($table, array $options = array()) {
1629
1630
1631