/
Database.php
4761 lines (4167 loc) 路 142 KB
/
Database.php
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
/**
* @defgroup Database Database
*
* This file deals with database interface functions
* and query specifics/optimisations.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Database
*/
namespace Wikimedia\Rdbms;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Wikimedia\ScopedCallback;
use Wikimedia\Timestamp\ConvertibleTimestamp;
use Wikimedia;
use BagOStuff;
use HashBagOStuff;
use LogicException;
use InvalidArgumentException;
use UnexpectedValueException;
use Exception;
use RuntimeException;
/**
* Relational database abstraction object
*
* @ingroup Database
* @since 1.28
*/
abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
/** @var string Server that this instance is currently connected to */
protected $server;
/** @var string User that this instance is currently connected under the name of */
protected $user;
/** @var string Password used to establish the current connection */
protected $password;
/** @var array[] Map of (table => (dbname, schema, prefix) map) */
protected $tableAliases = [];
/** @var string[] Map of (index alias => index) */
protected $indexAliases = [];
/** @var bool Whether this PHP instance is for a CLI script */
protected $cliMode;
/** @var string Agent name for query profiling */
protected $agent;
/** @var int Bitfield of class DBO_* constants */
protected $flags;
/** @var array LoadBalancer tracking information */
protected $lbInfo = [];
/** @var array|bool Variables use for schema element placeholders */
protected $schemaVars = false;
/** @var array Parameters used by initConnection() to establish a connection */
protected $connectionParams = [];
/** @var array SQL variables values to use for all new connections */
protected $connectionVariables = [];
/** @var string Current SQL query delimiter */
protected $delimiter = ';';
/** @var string|bool|null Stashed value of html_errors INI setting */
protected $htmlErrors;
/** @var int */
protected $nonNativeInsertSelectBatchSize = 10000;
/** @var BagOStuff APC cache */
protected $srvCache;
/** @var LoggerInterface */
protected $connLogger;
/** @var LoggerInterface */
protected $queryLogger;
/** @var callable Error logging callback */
protected $errorLogger;
/** @var callable Deprecation logging callback */
protected $deprecationLogger;
/** @var callable|null */
protected $profiler;
/** @var TransactionProfiler */
protected $trxProfiler;
/** @var DatabaseDomain */
protected $currentDomain;
/** @var IDatabase|null Lazy handle to the master DB this server replicates from */
private $lazyMasterHandle;
/** @var object|resource|null Database connection */
protected $conn = null;
/** @var bool Whether a connection handle is open (connection itself might be dead) */
protected $opened = false;
/** @var array Map of (name => 1) for locks obtained via lock() */
protected $sessionNamedLocks = [];
/** @var array Map of (table name => 1) for TEMPORARY tables */
protected $sessionTempTables = [];
/** @var int Whether there is an active transaction (1 or 0) */
protected $trxLevel = 0;
/** @var string Hexidecimal string if a transaction is active or empty string otherwise */
protected $trxShortId = '';
/** @var int Transaction status */
protected $trxStatus = self::STATUS_TRX_NONE;
/** @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR */
protected $trxStatusCause;
/** @var array|null Error details of the last statement-only rollback */
private $trxStatusIgnoredCause;
/** @var float|null UNIX timestamp at the time of BEGIN for the last transaction */
private $trxTimestamp = null;
/** @var float Replication lag estimate at the time of BEGIN for the last transaction */
private $trxReplicaLag = null;
/** @var string Name of the function that start the last transaction */
private $trxFname = null;
/** @var bool Whether possible write queries were done in the last transaction started */
private $trxDoneWrites = false;
/** @var bool Whether the current transaction was started implicitly due to DBO_TRX */
private $trxAutomatic = false;
/** @var int Counter for atomic savepoint identifiers (reset with each transaction) */
private $trxAtomicCounter = 0;
/** @var array List of (name, unique ID, savepoint ID) for each active atomic section level */
private $trxAtomicLevels = [];
/** @var bool Whether the current transaction was started implicitly by startAtomic() */
private $trxAutomaticAtomic = false;
/** @var string[] Write query callers of the current transaction */
private $trxWriteCallers = [];
/** @var float Seconds spent in write queries for the current transaction */
private $trxWriteDuration = 0.0;
/** @var int Number of write queries for the current transaction */
private $trxWriteQueryCount = 0;
/** @var int Number of rows affected by write queries for the current transaction */
private $trxWriteAffectedRows = 0;
/** @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries */
private $trxWriteAdjDuration = 0.0;
/** @var int Number of write queries counted in trxWriteAdjDuration */
private $trxWriteAdjQueryCount = 0;
/** @var array[] List of (callable, method name, atomic section id) */
private $trxIdleCallbacks = [];
/** @var array[] List of (callable, method name, atomic section id) */
private $trxPreCommitCallbacks = [];
/** @var array[] List of (callable, method name, atomic section id) */
private $trxEndCallbacks = [];
/** @var callable[] Map of (name => callable) */
private $trxRecurringCallbacks = [];
/** @var bool Whether to suppress triggering of transaction end callbacks */
private $trxEndCallbacksSuppressed = false;
/** @var int[] Prior flags member variable values */
private $priorFlags = [];
/** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
protected $affectedRowCount;
/** @var float UNIX timestamp */
private $lastPing = 0.0;
/** @var string The last SQL query attempted */
private $lastQuery = '';
/** @var float|bool UNIX timestamp of last write query */
private $lastWriteTime = false;
/** @var string|bool */
private $lastPhpError = false;
/** @var float Query rount trip time estimate */
private $lastRoundTripEstimate = 0.0;
/** @var string Lock granularity is on the level of the entire database */
const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
/** @var string The SCHEMA keyword refers to a grouping of tables in a database */
const ATTR_SCHEMAS_AS_TABLE_GROUPS = 'supports-schemas';
/** @var int New Database instance will not be connected yet when returned */
const NEW_UNCONNECTED = 0;
/** @var int New Database instance will already be connected when returned */
const NEW_CONNECTED = 1;
/** @var int Transaction is in a error state requiring a full or savepoint rollback */
const STATUS_TRX_ERROR = 1;
/** @var int Transaction is active and in a normal state */
const STATUS_TRX_OK = 2;
/** @var int No transaction is active */
const STATUS_TRX_NONE = 3;
/** @var string Idiom used when a cancelable atomic section started the transaction */
private static $NOT_APPLICABLE = 'n/a';
/** @var string Prefix to the atomic section counter used to make savepoint IDs */
private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
/** @var int Writes to this temporary table do not affect lastDoneWrites() */
private static $TEMP_NORMAL = 1;
/** @var int Writes to this temporary table effect lastDoneWrites() */
private static $TEMP_PSEUDO_PERMANENT = 2;
/** Number of times to re-try an operation in case of deadlock */
private static $DEADLOCK_TRIES = 4;
/** Minimum time to wait before retry, in microseconds */
private static $DEADLOCK_DELAY_MIN = 500000;
/** Maximum time to wait before retry */
private static $DEADLOCK_DELAY_MAX = 1500000;
/** How long before it is worth doing a dummy query to test the connection */
private static $PING_TTL = 1.0;
private static $PING_QUERY = 'SELECT 1 AS ping';
private static $TINY_WRITE_SEC = 0.010;
private static $SLOW_WRITE_SEC = 0.500;
private static $SMALL_WRITE_ROWS = 100;
/**
* @note exceptions for missing libraries/drivers should be thrown in initConnection()
* @param array $params Parameters passed from Database::factory()
*/
protected function __construct( array $params ) {
foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
$this->connectionParams[$name] = $params[$name];
}
$this->cliMode = $params['cliMode'];
// Agent name is added to SQL queries in a comment, so make sure it can't break out
$this->agent = str_replace( '/', '-', $params['agent'] );
$this->flags = $params['flags'];
if ( $this->flags & self::DBO_DEFAULT ) {
if ( $this->cliMode ) {
$this->flags &= ~self::DBO_TRX;
} else {
$this->flags |= self::DBO_TRX;
}
}
// Disregard deprecated DBO_IGNORE flag (T189999)
$this->flags &= ~self::DBO_IGNORE;
$this->connectionVariables = $params['variables'];
$this->srvCache = $params['srvCache'] ?? new HashBagOStuff();
$this->profiler = is_callable( $params['profiler'] ) ? $params['profiler'] : null;
$this->trxProfiler = $params['trxProfiler'];
$this->connLogger = $params['connLogger'];
$this->queryLogger = $params['queryLogger'];
$this->errorLogger = $params['errorLogger'];
$this->deprecationLogger = $params['deprecationLogger'];
if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
$this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'];
}
// Set initial dummy domain until open() sets the final DB/prefix
$this->currentDomain = new DatabaseDomain(
$params['dbname'] != '' ? $params['dbname'] : null,
$params['schema'] != '' ? $params['schema'] : null,
$params['tablePrefix']
);
}
/**
* Initialize the connection to the database over the wire (or to local files)
*
* @throws LogicException
* @throws InvalidArgumentException
* @throws DBConnectionError
* @since 1.31
*/
final public function initConnection() {
if ( $this->isOpen() ) {
throw new LogicException( __METHOD__ . ': already connected.' );
}
// Establish the connection
$this->doInitConnection();
}
/**
* Actually connect to the database over the wire (or to local files)
*
* @throws InvalidArgumentException
* @throws DBConnectionError
* @since 1.31
*/
protected function doInitConnection() {
if ( strlen( $this->connectionParams['user'] ) ) {
$this->open(
$this->connectionParams['host'],
$this->connectionParams['user'],
$this->connectionParams['password'],
$this->connectionParams['dbname'],
$this->connectionParams['schema'],
$this->connectionParams['tablePrefix']
);
} else {
throw new InvalidArgumentException( "No database user provided." );
}
}
/**
* Open a new connection to the database (closing any existing one)
*
* @param string $server Database server host
* @param string $user Database user name
* @param string $password Database user password
* @param string $dbName Database name
* @param string|null $schema Database schema name
* @param string $tablePrefix Table prefix
* @return bool
* @throws DBConnectionError
*/
abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
/**
* Construct a Database subclass instance given a database type and parameters
*
* This also connects to the database immediately upon object construction
*
* @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
* @param array $p Parameter map with keys:
* - host : The hostname of the DB server
* - user : The name of the database user the client operates under
* - password : The password for the database user
* - dbname : The name of the database to use where queries do not specify one.
* The database must exist or an error might be thrown. Setting this to the empty string
* will avoid any such errors and make the handle have no implicit database scope. This is
* useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
* "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
* in which user names and such are defined, e.g. users are database-specific in Postgres.
* - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
* equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
* - tablePrefix : Optional table prefix that is implicitly added on to all table names
* recognized in queries. This can be used in place of schemas for handle site farms.
* - flags : Optional bitfield of DBO_* constants that define connection, protocol,
* buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
* flag in place UNLESS this this database simply acts as a key/value store.
* - driver: Optional name of a specific DB client driver. For MySQL, there is only the
* 'mysqli' driver; the old one 'mysql' has been removed.
* - variables: Optional map of session variables to set after connecting. This can be
* used to adjust lock timeouts or encoding modes and the like.
* - connLogger: Optional PSR-3 logger interface instance.
* - queryLogger: Optional PSR-3 logger interface instance.
* - profiler : Optional callback that takes a section name argument and returns
* a ScopedCallback instance that ends the profile section in its destructor.
* These will be called in query(), using a simplified version of the SQL that
* also includes the agent as a SQL comment.
* - trxProfiler: Optional TransactionProfiler instance.
* - errorLogger: Optional callback that takes an Exception and logs it.
* - deprecationLogger: Optional callback that takes a string and logs it.
* - cliMode: Whether to consider the execution context that of a CLI script.
* - agent: Optional name used to identify the end-user in query profiling/logging.
* - srvCache: Optional BagOStuff instance to an APC-style cache.
* - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
* @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
* @return Database|null If the database driver or extension cannot be found
* @throws InvalidArgumentException If the database driver or extension cannot be found
* @since 1.18
*/
final public static function factory( $dbType, $p = [], $connect = self::NEW_CONNECTED ) {
$class = self::getClass( $dbType, $p['driver'] ?? null );
if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
// Resolve some defaults for b/c
$p['host'] = $p['host'] ?? false;
$p['user'] = $p['user'] ?? false;
$p['password'] = $p['password'] ?? false;
$p['dbname'] = $p['dbname'] ?? false;
$p['flags'] = $p['flags'] ?? 0;
$p['variables'] = $p['variables'] ?? [];
$p['tablePrefix'] = $p['tablePrefix'] ?? '';
$p['schema'] = $p['schema'] ?? null;
$p['cliMode'] = $p['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
$p['agent'] = $p['agent'] ?? '';
if ( !isset( $p['connLogger'] ) ) {
$p['connLogger'] = new NullLogger();
}
if ( !isset( $p['queryLogger'] ) ) {
$p['queryLogger'] = new NullLogger();
}
$p['profiler'] = $p['profiler'] ?? null;
if ( !isset( $p['trxProfiler'] ) ) {
$p['trxProfiler'] = new TransactionProfiler();
}
if ( !isset( $p['errorLogger'] ) ) {
$p['errorLogger'] = function ( Exception $e ) {
trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
};
}
if ( !isset( $p['deprecationLogger'] ) ) {
$p['deprecationLogger'] = function ( $msg ) {
trigger_error( $msg, E_USER_DEPRECATED );
};
}
/** @var Database $conn */
$conn = new $class( $p );
if ( $connect == self::NEW_CONNECTED ) {
$conn->initConnection();
}
} else {
$conn = null;
}
return $conn;
}
/**
* @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
* @param string|null $driver Optional name of a specific DB client driver
* @return array Map of (Database::ATTR_* constant => value) for all such constants
* @throws InvalidArgumentException
* @since 1.31
*/
final public static function attributesFromType( $dbType, $driver = null ) {
static $defaults = [
self::ATTR_DB_LEVEL_LOCKING => false,
self::ATTR_SCHEMAS_AS_TABLE_GROUPS => false
];
$class = self::getClass( $dbType, $driver );
return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
}
/**
* @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
* @param string|null $driver Optional name of a specific DB client driver
* @return string Database subclass name to use
* @throws InvalidArgumentException
*/
private static function getClass( $dbType, $driver = null ) {
// For database types with built-in support, the below maps type to IDatabase
// implementations. For types with multipe driver implementations (PHP extensions),
// an array can be used, keyed by extension name. In case of an array, the
// optional 'driver' parameter can be used to force a specific driver. Otherwise,
// we auto-detect the first available driver. For types without built-in support,
// an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
static $builtinTypes = [
'mssql' => DatabaseMssql::class,
'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
'sqlite' => DatabaseSqlite::class,
'postgres' => DatabasePostgres::class,
];
$dbType = strtolower( $dbType );
$class = false;
if ( isset( $builtinTypes[$dbType] ) ) {
$possibleDrivers = $builtinTypes[$dbType];
if ( is_string( $possibleDrivers ) ) {
$class = $possibleDrivers;
} elseif ( (string)$driver !== '' ) {
if ( !isset( $possibleDrivers[$driver] ) ) {
throw new InvalidArgumentException( __METHOD__ .
" type '$dbType' does not support driver '{$driver}'" );
}
$class = $possibleDrivers[$driver];
} else {
foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
if ( extension_loaded( $posDriver ) ) {
$class = $possibleClass;
break;
}
}
}
} else {
$class = 'Database' . ucfirst( $dbType );
}
if ( $class === false ) {
throw new InvalidArgumentException( __METHOD__ .
" no viable database extension found for type '$dbType'" );
}
return $class;
}
/**
* @return array Map of (Database::ATTR_* constant => value
* @since 1.31
*/
protected static function getAttributes() {
return [];
}
/**
* Set the PSR-3 logger interface to use for query logging. (The logger
* interfaces for connection logging and error logging can be set with the
* constructor.)
*
* @param LoggerInterface $logger
*/
public function setLogger( LoggerInterface $logger ) {
$this->queryLogger = $logger;
}
public function getServerInfo() {
return $this->getServerVersion();
}
public function bufferResults( $buffer = null ) {
$res = !$this->getFlag( self::DBO_NOBUFFER );
if ( $buffer !== null ) {
$buffer
? $this->clearFlag( self::DBO_NOBUFFER )
: $this->setFlag( self::DBO_NOBUFFER );
}
return $res;
}
public function trxLevel() {
return $this->trxLevel;
}
public function trxTimestamp() {
return $this->trxLevel ? $this->trxTimestamp : null;
}
/**
* @return int One of the STATUS_TRX_* class constants
* @since 1.31
*/
public function trxStatus() {
return $this->trxStatus;
}
public function tablePrefix( $prefix = null ) {
$old = $this->currentDomain->getTablePrefix();
if ( $prefix !== null ) {
$this->currentDomain = new DatabaseDomain(
$this->currentDomain->getDatabase(),
$this->currentDomain->getSchema(),
$prefix
);
}
return $old;
}
public function dbSchema( $schema = null ) {
if ( strlen( $schema ) && $this->getDBname() === null ) {
throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set." );
}
$old = $this->currentDomain->getSchema();
if ( $schema !== null ) {
$this->currentDomain = new DatabaseDomain(
$this->currentDomain->getDatabase(),
// DatabaseDomain uses null for unspecified schemas
strlen( $schema ) ? $schema : null,
$this->currentDomain->getTablePrefix()
);
}
return (string)$old;
}
/**
* @return string Schema to use to qualify relations in queries
*/
protected function relationSchemaQualifier() {
return $this->dbSchema();
}
public function getLBInfo( $name = null ) {
if ( is_null( $name ) ) {
return $this->lbInfo;
}
if ( array_key_exists( $name, $this->lbInfo ) ) {
return $this->lbInfo[$name];
}
return null;
}
public function setLBInfo( $name, $value = null ) {
if ( is_null( $value ) ) {
$this->lbInfo = $name;
} else {
$this->lbInfo[$name] = $value;
}
}
public function setLazyMasterHandle( IDatabase $conn ) {
$this->lazyMasterHandle = $conn;
}
/**
* @return IDatabase|null
* @see setLazyMasterHandle()
* @since 1.27
*/
protected function getLazyMasterHandle() {
return $this->lazyMasterHandle;
}
public function implicitGroupby() {
return true;
}
public function implicitOrderby() {
return true;
}
public function lastQuery() {
return $this->lastQuery;
}
public function doneWrites() {
return (bool)$this->lastWriteTime;
}
public function lastDoneWrites() {
return $this->lastWriteTime ?: false;
}
public function writesPending() {
return $this->trxLevel && $this->trxDoneWrites;
}
public function writesOrCallbacksPending() {
return $this->trxLevel && (
$this->trxDoneWrites ||
$this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
);
}
public function preCommitCallbacksPending() {
return $this->trxLevel && $this->trxPreCommitCallbacks;
}
/**
* @return string|null
*/
final protected function getTransactionRoundId() {
// If transaction round participation is enabled, see if one is active
if ( $this->getFlag( self::DBO_TRX ) ) {
$id = $this->getLBInfo( 'trxRoundId' );
return is_string( $id ) ? $id : null;
}
return null;
}
public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
if ( !$this->trxLevel ) {
return false;
} elseif ( !$this->trxDoneWrites ) {
return 0.0;
}
switch ( $type ) {
case self::ESTIMATE_DB_APPLY:
return $this->pingAndCalculateLastTrxApplyTime();
default: // everything
return $this->trxWriteDuration;
}
}
/**
* @return float Time to apply writes to replicas based on trxWrite* fields
*/
private function pingAndCalculateLastTrxApplyTime() {
$this->ping( $rtt );
$rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
$applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
// For omitted queries, make them count as something at least
$omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
$applyTime += self::$TINY_WRITE_SEC * $omitted;
return $applyTime;
}
public function pendingWriteCallers() {
return $this->trxLevel ? $this->trxWriteCallers : [];
}
public function pendingWriteRowsAffected() {
return $this->trxWriteAffectedRows;
}
/**
* List the methods that have write queries or callbacks for the current transaction
*
* This method should not be used outside of Database/LoadBalancer
*
* @return string[]
* @since 1.32
*/
public function pendingWriteAndCallbackCallers() {
$fnames = $this->pendingWriteCallers();
foreach ( [
$this->trxIdleCallbacks,
$this->trxPreCommitCallbacks,
$this->trxEndCallbacks
] as $callbacks ) {
foreach ( $callbacks as $callback ) {
$fnames[] = $callback[1];
}
}
return $fnames;
}
/**
* @return string
*/
private function flatAtomicSectionList() {
return array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
return $accum === null ? $v[0] : "$accum, " . $v[0];
} );
}
public function isOpen() {
return $this->opened;
}
public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
if ( ( $flag & self::DBO_IGNORE ) ) {
throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
}
if ( $remember === self::REMEMBER_PRIOR ) {
array_push( $this->priorFlags, $this->flags );
}
$this->flags |= $flag;
}
public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
if ( ( $flag & self::DBO_IGNORE ) ) {
throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
}
if ( $remember === self::REMEMBER_PRIOR ) {
array_push( $this->priorFlags, $this->flags );
}
$this->flags &= ~$flag;
}
public function restoreFlags( $state = self::RESTORE_PRIOR ) {
if ( !$this->priorFlags ) {
return;
}
if ( $state === self::RESTORE_INITIAL ) {
$this->flags = reset( $this->priorFlags );
$this->priorFlags = [];
} else {
$this->flags = array_pop( $this->priorFlags );
}
}
public function getFlag( $flag ) {
return (bool)( $this->flags & $flag );
}
/**
* @param string $name Class field name
* @return mixed
* @deprecated Since 1.28
*/
public function getProperty( $name ) {
return $this->$name;
}
public function getDomainID() {
return $this->currentDomain->getId();
}
final public function getWikiID() {
return $this->getDomainID();
}
/**
* Get information about an index into an object
* @param string $table Table name
* @param string $index Index name
* @param string $fname Calling function name
* @return mixed Database-specific index description class or false if the index does not exist
*/
abstract function indexInfo( $table, $index, $fname = __METHOD__ );
/**
* Wrapper for addslashes()
*
* @param string $s String to be slashed.
* @return string Slashed string.
*/
abstract function strencode( $s );
/**
* Set a custom error handler for logging errors during database connection
*/
protected function installErrorHandler() {
$this->lastPhpError = false;
$this->htmlErrors = ini_set( 'html_errors', '0' );
set_error_handler( [ $this, 'connectionErrorLogger' ] );
}
/**
* Restore the previous error handler and return the last PHP error for this DB
*
* @return bool|string
*/
protected function restoreErrorHandler() {
restore_error_handler();
if ( $this->htmlErrors !== false ) {
ini_set( 'html_errors', $this->htmlErrors );
}
return $this->getLastPHPError();
}
/**
* @return string|bool Last PHP error for this DB (typically connection errors)
*/
protected function getLastPHPError() {
if ( $this->lastPhpError ) {
$error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
$error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
return $error;
}
return false;
}
/**
* Error handler for logging errors during database connection
* This method should not be used outside of Database classes
*
* @param int $errno
* @param string $errstr
*/
public function connectionErrorLogger( $errno, $errstr ) {
$this->lastPhpError = $errstr;
}
/**
* Create a log context to pass to PSR-3 logger functions.
*
* @param array $extras Additional data to add to context
* @return array
*/
protected function getLogContext( array $extras = [] ) {
return array_merge(
[
'db_server' => $this->server,
'db_name' => $this->getDBname(),
'db_user' => $this->user,
],
$extras
);
}
final public function close() {
$exception = null; // error to throw after disconnecting
$wasOpen = $this->opened;
// This should mostly do nothing if the connection is already closed
if ( $this->conn ) {
// Roll back any dangling transaction first
if ( $this->trxLevel ) {
if ( $this->trxAtomicLevels ) {
// Cannot let incomplete atomic sections be committed
$levels = $this->flatAtomicSectionList();
$exception = new DBUnexpectedError(
$this,
__METHOD__ . ": atomic sections $levels are still open."
);
} elseif ( $this->trxAutomatic ) {
// Only the connection manager can commit non-empty DBO_TRX transactions
// (empty ones we can silently roll back)
if ( $this->writesOrCallbacksPending() ) {
$exception = new DBUnexpectedError(
$this,
__METHOD__ .
": mass commit/rollback of peer transaction required (DBO_TRX set)."
);
}
} else {
// Manual transactions should have been committed or rolled
// back, even if empty.
$exception = new DBUnexpectedError(
$this,
__METHOD__ . ": transaction is still open (from {$this->trxFname})."
);
}
if ( $this->trxEndCallbacksSuppressed ) {
$exception = $exception ?: new DBUnexpectedError(
$this,
__METHOD__ . ': callbacks are suppressed; cannot properly commit.'
);
}
// Rollback the changes and run any callbacks as needed
$this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
}
// Close the actual connection in the binding handle
$closed = $this->closeConnection();
} else {
$closed = true; // already closed; nothing to do
}
$this->conn = false;
$this->opened = false;
// Throw any unexpected errors after having disconnected
if ( $exception instanceof Exception ) {
throw $exception;
}
// Note that various subclasses call close() at the start of open(), which itself is
// called by replaceLostConnection(). In that case, just because onTransactionResolution()
// callbacks are pending does not mean that an exception should be thrown. Rather, they
// will be executed after the reconnection step.
if ( $wasOpen ) {
// Sanity check that no callbacks are dangling
$fnames = $this->pendingWriteAndCallbackCallers();
if ( $fnames ) {
throw new RuntimeException(
"Transaction callbacks are still pending:\n" . implode( ', ', $fnames )
);
}
}
return $closed;
}
/**
* Make sure there is an open connection handle (alive or not) as a sanity check
*
* This guards against fatal errors to the binding handle not being defined
* in cases where open() was never called or close() was already called
*
* @throws DBUnexpectedError
*/
final protected function assertHasConnectionHandle() {
if ( !$this->isOpen() ) {
throw new DBUnexpectedError( $this, "DB connection was already closed." );
}
}
/**
* Make sure that this server is not marked as a replica nor read-only as a sanity check
*
* @throws DBReadOnlyRoleError
* @throws DBReadOnlyError
*/
protected function assertIsWritableMaster() {
if ( $this->getLBInfo( 'replica' ) === true ) {
throw new DBReadOnlyRoleError(
$this,
'Write operations are not allowed on replica database connections.'
);
}
$reason = $this->getReadOnlyReason();
if ( $reason !== false ) {
throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
}
}
/**
* Closes underlying database connection
* @since 1.20
* @return bool Whether connection was closed successfully
*/
abstract protected function closeConnection();
/**
* @deprecated since 1.32
* @param string $error Fallback message, if none is given by DB
* @throws DBConnectionError
*/
public function reportConnectionError( $error = 'Unknown error' ) {
call_user_func( $this->deprecationLogger, 'Use of ' . __METHOD__ . ' is deprecated.' );
throw new DBConnectionError( $this, $this->lastError() ?: $error );
}
/**
* Run a query and return a DBMS-dependent wrapper or boolean
*
* This is meant to handle the basic command of actually sending a query to the
* server via the driver. No implicit transaction, reconnection, nor retry logic
* should happen here. The higher level query() method is designed to handle those
* sorts of concerns. This method should not trigger such higher level methods.
*
* The lastError() and lastErrno() methods should meaningfully reflect what error,
* if any, occured during the last call to this method. Methods like executeQuery(),