-
Notifications
You must be signed in to change notification settings - Fork 3
/
database.inc
2910 lines (2672 loc) · 88.9 KB
/
database.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// $Id$
/**
* @file
* 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.
*/
/**
* @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
* the ability to support multiple database servers easily. The intent of
* 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
* a unified way. It also provides a structured interface for dynamically
* 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 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.
*
* 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', 0, 10, array(':uid' => $uid));
* 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 iterate over the result set using
* foreach ().
*
* All queries are passed as a prepared statement string. A
* prepared statement is a "template" of a query that omits literal or variable
* values in favor of placeholders. The values to place into those
* placeholders are passed separately, and the database driver handles
* inserting the values into the query in a secure fashion. That means you
* should never quote or string-escape a value to be inserted into the query.
*
* There are two formats for placeholders: named and unnamed. Named placeholders
* are strongly preferred in all cases as they are more flexible and
* self-documenting. Named placeholders should start with a colon ":" and can be
* followed by one or more letters, numbers or underscores.
*
* Named placeholders begin with a colon followed by a unique string. Example:
* @code
* SELECT nid, title FROM {node} WHERE uid=:uid;
* @endcode
*
* ":uid" is a placeholder that will be replaced with a literal value when
* 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
* 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
* corresponding value to use. The array may be in any order.
*
* Unnamed placeholders are simply a question mark. Example:
* @code
* SELECT nid, title FROM {node} WHERE uid=?;
* @endcode
*
* In this case, the array of arguments must be an indexed array of values to
* use in the exact same order as the placeholders in the query.
*
* Note that placeholders should be a "complete" value. For example, when
* running a LIKE query the SQL wildcard character, %, should be part of the
* value, not the query itself. Thus, the following is incorrect:
* @code
* SELECT nid, title FROM {node} WHERE title LIKE :title%;
* @endcode
* It should instead read:
* @code
* SELECT nid, title FROM {node} WHERE title LIKE :title;
* @endcode
* 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
* into the query as one big string but as an explicitly separate value, the
* database server knows where the query ends and a value begins. That is
* considerably more secure against SQL injection than trying to remember
* which values need quotation marks and string escaping and which don't.
*
* INSERT, UPDATE, and DELETE queries need special care in order to behave
* consistently across all different databases. Therefore, they use a special
* object-oriented API for defining a query structurally. For example, rather
* than:
* @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('node')->fields($fields)->execute();
* @endcode
* This method allows databases that need special data type handling to do so,
* while also allowing optimizations such as multi-insert queries. UPDATE and
* DELETE queries have a similar pattern.
*
* Drupal also supports transactions, including a transparent fallback for
* databases that do not support transactions. To start a new transaction,
* simply call $txn = db_transaction(); in your own code. The transaction will
* 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();
*
* try {
* $id = db_insert('example')
* ->fields(array(
* 'field1' => 'mystring',
* 'field2' => 5,
* ))
* ->execute();
*
* my_other_function($id);
*
* return $id;
* }
* catch (Exception $e) {
* // Something went wrong somewhere, so roll back now.
* $txn->rollback();
* // Log the exception to watchdog.
* watchdog_exception('type', $e);
* }
*
* // $txn goes out of scope here. Unless the transaction was rolled back, it
* // gets automatically commited here.
* }
*
* 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
*
* @link http://drupal.org/developing/api/database
*/
/**
* 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.
*
* @see http://php.net/manual/en/book.pdo.php
*/
abstract class DatabaseConnection extends PDO {
/**
* The database target this connection is for.
*
* We need this information for later auditing and logging.
*
* @var string
*/
protected $target = NULL;
/**
* The key representing this connection.
*
* The key is a unique string which identifies a database connection. A
* connection can be a single server or a cluster of master and slaves (use
* target to pick between master and slave).
*
* @var string
*/
protected $key = NULL;
/**
* The current database logging object for this connection.
*
* @var DatabaseLog
*/
protected $logger = NULL;
/**
* Tracks the number of "layers" of transactions currently active.
*
* On many databases transactions cannot nest. Instead, we track
* nested calls to transactions and collapse them into a single
* transaction.
*
* @var array
*/
protected $transactionLayers = array();
/**
* Index of what driver-specific class to use for various operations.
*
* @var array
*/
protected $driverClasses = array();
/**
* The name of the Statement class for this connection.
*
* @var string
*/
protected $statementClass = 'DatabaseStatementBase';
/**
* Whether this database connection supports transactions.
*
* @var bool
*/
protected $transactionSupport = TRUE;
/**
* Whether this database connection supports transactional DDL.
*
* Set to FALSE by default because few databases support this feature.
*
* @var bool
*/
protected $transactionalDDLSupport = FALSE;
/**
* An index used to generate unique temporary table names.
*
* @var integer
*/
protected $temporaryNameIndex = 0;
/**
* The connection information for this connection object.
*
* @var array
*/
protected $connectionOptions = array();
/**
* The schema object for this connection.
*
* @var object
*/
protected $schema = NULL;
/**
* 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();
function __construct($dsn, $username, $password, $driver_options = array()) {
// Initialize and prepare the connection prefix.
$this->setPrefix(isset($this->connectionOptions['prefix']) ? $this->connectionOptions['prefix'] : '');
// Because the other methods don't seem to work right.
$driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
// Call PDO::__construct and PDO::setAttribute.
parent::__construct($dsn, $username, $password, $driver_options);
// Set a specific PDOStatement class if the driver requires that.
if (!empty($this->statementClass)) {
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($this->statementClass, array($this)));
}
}
/**
* Returns the default query options for any given query.
*
* A given query can be customized with a number of option flags in an
* associative array:
* - 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
* is not available, it will silently fall back to the "default" target.
* If multiple databases connections are specified with the same target,
* one will be selected at random for the duration of the request.
* - 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, 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
* - return: Depending on the type of query, different return values may be
* meaningful. This directive instructs the system which type of return
* value is desired. The system will generally set the correct value
* automatically, so it is extremely rare that a module developer will ever
* need to specify this value. Setting it incorrectly will likely lead to
* unpredictable results or fatal errors. Legal values include:
* - Database::RETURN_STATEMENT: Return the prepared statement object for
* 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.
* - Database::RETURN_AFFECTED: Return the number of rows affected by an
* UPDATE or DELETE query. Be aware that means the number of rows actually
* changed, not the number of rows matched by the WHERE clause.
* - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
* created by an INSERT statement on a table that contains a serial
* column.
* - Database::RETURN_NULL: Do not return anything, as there is no
* meaningful value to return. That is the case for INSERT queries on
* tables that do not contain a serial column.
* - 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
* further up the call chain can take an appropriate action. To suppress
* 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,
);
}
/**
* Returns the connection information for this connection object.
*
* 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;
}
/**
* 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();
}
}
/**
* Appends 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
* tables, allowing Drupal to coexist with other systems in the same database
* and/or schema if necessary.
*
* @param $sql
* A string containing a partial or entire SQL query.
*
* @return
* The properly-prefixed string.
*/
public function prefixTables($sql) {
// Replace specific table prefixes first.
foreach ($this->prefixes as $key => $val) {
$sql = strtr($sql, array('{' . $key . '}' => $val . $key));
}
// Then replace remaining tables with the default prefix.
return strtr($sql, array('{' => $this->defaultPrefix , '}' => ''));
}
/**
* 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') {
if (isset($this->prefixes[$table])) {
return $this->prefixes[$table];
}
else {
return $this->defaultPrefix;
}
}
/**
* Prepares a query string and returns the prepared statement.
*
* This method caches prepared statements, reusing them when
* possible. It also prefixes tables names enclosed in curly-braces.
*
* @param $query
* The query string as SQL, with curly-braces surrounding the
* table names.
*
* @return DatabaseStatementInterface
* A PDO prepared statement ready for its execute() method.
*/
public function prepareQuery($query) {
$query = $this->prefixTables($query);
// Call PDO::prepare.
return parent::prepare($query);
}
/**
* Tells this connection object what its target value is.
*
* This is needed for logging and auditing. It's sloppy to do in the
* constructor because the constructor for child classes has a different
* signature. We therefore also ensure that this function is only ever
* called once.
*
* @param $target
* The target this connection is for. Set to NULL (default) to disable
* 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;
}
/**
* Tells this connection object what its key is.
*
* @param $target
* The key this connection is for.
*/
public function setKey($key) {
if (!isset($this->key)) {
$this->key = $key;
}
}
/**
* Returns the key this connection is associated with.
*
* @return
* The key of this connection.
*/
public function getKey() {
return $this->key;
}
/**
* Associates a logging object with this connection.
*
* @param $logger
* The logging object we want to use.
*/
public function setLogger(DatabaseLog $logger) {
$this->logger = $logger;
}
/**
* Gets the current logging object for this connection.
*
* @return DatabaseLog
* The current logging object for this connection. If there isn't one,
* NULL is returned.
*/
public function getLogger() {
return $this->logger;
}
/**
* Creates the appropriate sequence name for a given table and serial field.
*
* This information is exposed to all database drivers, although it is only
* useful on some of them. This method is table prefix-aware.
*
* @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');
}
/**
* Executes a query string against the database.
*
* This method provides a central handler for the actual execution of every
* query. All queries executed by Drupal are executed as PDO prepared
* statements.
*
* @param $query
* The query to execute. In most cases this will be a string containing
* an SQL query with placeholders. An already-prepared instance of
* 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.
* It is extremely rare that module code will need to pass a statement
* object to this method. It is used primarily for database drivers for
* databases that require special LOB field handling.
* @param $args
* An array of arguments for the prepared statement. If the prepared
* statement uses ? placeholders, this array must be an indexed array.
* If it contains named placeholders, it must be an associative array.
* @param $options
* An associative array of options to control how the query is run. See
* the documentation for DatabaseConnection::defaultOptions() for details.
*
* @return DatabaseStatementInterface
* 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 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.
*
* @throws PDOException
*/
public function query($query, array $args = array(), $options = array()) {
// Use default values if not already set.
$options += $this->defaultOptions();
try {
// We allow either a pre-bound statement object or a literal string.
// In either case, we want to end up with an executed statement object,
// which we pass to PDOStatement::execute.
if ($query instanceof DatabaseStatementInterface) {
$stmt = $query;
$stmt->execute(NULL, $options);
}
else {
$this->expandArguments($query, $args);
$stmt = $this->prepareQuery($query);
$stmt->execute($args, $options);
}
// 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) {
if ($options['throw_exception']) {
// Add additional debug information.
if ($query instanceof DatabaseStatementInterface) {
$e->query_string = $stmt->getQueryString();
}
else {
$e->query_string = $query;
}
$e->args = $args;
throw $e;
}
return NULL;
}
}
/**
* Expands out shorthand placeholders.
*
* Drupal supports an alternate syntax for doing arrays of values. We
* therefore need to expand them out into a full, executable query string.
*
* @param $query
* The query string to modify.
* @param $args
* The arguments for the query.
*
* @return
* TRUE if the query was modified, FALSE otherwise.
*/
protected function expandArguments(&$query, &$args) {
$modified = FALSE;
// 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;
}
// 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
// query contains the placeholders :foo and :foobar, and :foo has an
// 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;
}
return $modified;
}
/**
* 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.
* @param array $files
* The name of the files in which the driver-specific class can be.
* @param $use_autoload
* If TRUE, attempt to load classes using PHP's autoload capability
* as well as the manual approach here.
* @return string
* The name of the class that should be used for this driver.
*/
public function getDriverClass($class, array $files = array(), $use_autoload = FALSE) {
if (empty($this->driverClasses[$class])) {
$driver = $this->driver();
$this->driverClasses[$class] = $class . '_' . $driver;
Database::loadDriverFile($driver, $files);
if (!class_exists($this->driverClasses[$class], $use_autoload)) {
$this->driverClasses[$class] = $class;
}
}
return $this->driverClasses[$class];
}
/**
* Prepares and returns a SELECT query object.
*
* @param $table
* The base table for this query, that is, the first table in the FROM
* clause. This table will also be used as the "base" table for query_alter
* hook implementations.
* @param $alias
* The alias of the base table of this query.
* @param $options
* An array of options on the query.
*
* @return SelectQueryInterface
* 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
*/
public function select($table, $alias = NULL, array $options = array()) {
$class = $this->getDriverClass('SelectQuery', array('query.inc', 'select.inc'));
return new $class($table, $alias, $this, $options);
}
/**
* Prepares and returns an INSERT query object.
*
* @param $options
* An array of options on the query.
*
* @return InsertQuery
* A new InsertQuery object.
*
* @see InsertQuery
*/
public function insert($table, array $options = array()) {
$class = $this->getDriverClass('InsertQuery', array('query.inc'));
return new $class($this, $table, $options);
}
/**
* Prepares and returns a MERGE query object.
*
* @param $options
* An array of options on the query.
*
* @return MergeQuery
* A new MergeQuery object.
*
* @see MergeQuery
*/
public function merge($table, array $options = array()) {
$class = $this->getDriverClass('MergeQuery', array('query.inc'));
return new $class($this, $table, $options);
}
/**
* Prepares and returns an UPDATE query object.
*
* @param $options
* An array of options on the query.
*
* @return UpdateQuery
* A new UpdateQuery object.
*
* @see UpdateQuery
*/
public function update($table, array $options = array()) {
$class = $this->getDriverClass('UpdateQuery', array('query.inc'));
return new $class($this, $table, $options);
}
/**
* Prepares and returns a DELETE query object.
*
* @param $options
* An array of options on the query.
*
* @return DeleteQuery
* A new DeleteQuery object.
*
* @see DeleteQuery
*/
public function delete($table, array $options = array()) {
$class = $this->getDriverClass('DeleteQuery', array('query.inc'));
return new $class($this, $table, $options);
}
/**
* Prepares and returns a TRUNCATE query object.
*
* @param $options
* An array of options on the query.
*
* @return TruncateQuery
* A new TruncateQuery object.
*
* @see TruncateQuery
*/
public function truncate($table, array $options = array()) {
$class = $this->getDriverClass('TruncateQuery', array('query.inc'));
return new $class($this, $table, $options);
}
/**
* Returns a DatabaseSchema object for manipulating the schema.
*
* This method will lazy-load the appropriate schema library file.
*
* @return DatabaseSchema
* The DatabaseSchema object for this connection.
*/
public function schema() {
if (empty($this->schema)) {
$class = $this->getDriverClass('DatabaseSchema', array('schema.inc'));
if (class_exists($class)) {
$this->schema = new $class($this);
}
}
return $this->schema;
}
/**
* 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) {
return preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
}
/**
* 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);
}
/**
* Escapes an alias name string.
*
* Force all alias names to be strictly alphanumeric-plus-underscore. In
* contrast to DatabaseConnection::escapeField() /
* DatabaseConnection::escapeTable(), this doesn't allow the period (".")
* because that is not allowed in aliases.
*
* @return
* The sanitized field name string.
*/
public function escapeAlias($field) {
return preg_replace('/[^A-Za-z0-9_]+/', '', $field);
}
/**
* Escapes characters that work as wildcard characters in a LIKE pattern.
*
* The wildcard characters "%" and "_" as well as backslash are prefixed with
* a backslash. Use this to do a search for a verbatim string without any
* 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.
*
* @return
* The escaped string.
*/
public function escapeLike($string) {
return addcslashes($string, '\%_');
}
/**
* Determines if there is an active transaction open.
*
* @return
* TRUE if we're currently in a transaction, FALSE otherwise.
*/
public function inTransaction() {
return ($this->transactionDepth() > 0);
}
/**
* Determines current transaction depth.
*/
public function transactionDepth() {
return count($this->transactionLayers);
}
/**
* Returns a new DatabaseTransaction object on this connection.
*
* @param $name
* Optional name of the savepoint.
*
* @see DatabaseTransaction
*/
public function startTransaction($name = '') {
$class = $this->getDriverClass('DatabaseTransaction');
return new $class($this, $name);
}
/**
* Rolls back the transaction entirely or to a named savepoint.
*
* This method throws an exception if no transaction is active.
*
* @param $savepoint_name
* The name of the savepoint. The default, 'drupal_transaction', will roll
* the entire transaction back.
*
* @throws DatabaseTransactionNoActiveException
*
* @see DatabaseTransaction::rollback()
*/
public function rollback($savepoint_name = 'drupal_transaction') {
if (!$this->supportsTransactions()) {
return;
}
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;
}
// 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;
}
}
parent::rollBack();
}
/**
* Increases the depth of transaction nesting.
*
* If no transaction is already active, we begin a new transaction.
*
* @throws DatabaseTransactionNameNonUniqueException
*
* @see DatabaseTransaction
*/
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);
}
else {
parent::beginTransaction();
}
$this->transactionLayers[$name] = $name;
}
/**
* Decreases the depth of transaction nesting.