MediaWiki master
DatabaseMySQL.php
Go to the documentation of this file.
1<?php
6namespace Wikimedia\Rdbms;
7
8use mysqli;
9use mysqli_result;
10use RuntimeException;
11use Wikimedia\IPUtils;
15
27class DatabaseMySQL extends Database {
29 private $sslKeyPath;
31 private $sslCertPath;
33 private $sslCAFile;
35 private $sslCAPath;
41 private $sslCiphers;
43 private $utf8Mode;
44
46 protected $platform;
47
51 private $sessionLastAutoRowId;
52
72 public function __construct( array $params ) {
73 foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
74 $var = "ssl{$name}";
75 if ( isset( $params[$var] ) ) {
76 $this->$var = $params[$var];
77 }
78 }
79 $this->utf8Mode = !empty( $params['utf8Mode'] );
80 parent::__construct( $params );
81 $this->platform = new MySQLPlatform(
82 $this,
83 $this->logger,
84 $this->currentDomain,
85 $this->errorLogger
86 );
87 $this->replicationReporter = new MysqlReplicationReporter(
88 $params['topologyRole'],
89 $this->logger,
90 $params['srvCache'],
91 $params['lagDetectionMethod'] ?? 'Seconds_Behind_Master',
92 $params['lagDetectionOptions'] ?? [],
93 !empty( $params['useGTIDs' ] )
94 );
95 }
96
100 public function getType() {
101 return 'mysql';
102 }
103
105 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
106 $this->close( __METHOD__ );
107
108 if ( $schema !== null ) {
109 throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
110 }
111
112 $this->installErrorHandler();
113 try {
114 $this->conn = $this->mysqlConnect( $server, $user, $password, $db );
115 } catch ( RuntimeException $e ) {
116 $this->restoreErrorHandler();
117 throw $this->newExceptionAfterConnectError( $e->getMessage() );
118 }
119 $error = $this->restoreErrorHandler();
120
121 if ( !$this->conn ) {
122 throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
123 }
124
125 try {
126 $this->currentDomain = new DatabaseDomain(
127 ( $db !== '' ) ? $db : null,
128 null,
129 $tablePrefix
130 );
131 $this->platform->setCurrentDomain( $this->currentDomain );
132
133 $set = [];
134 if ( !$this->flagsHolder->getFlag( self::DBO_GAUGE ) ) {
135 // Abstract over any excessive MySQL defaults
136 $set[] = 'group_concat_max_len = 262144';
137 // Set any custom settings defined by site config
138 // https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html
139 foreach ( $this->connectionVariables as $var => $val ) {
140 // Escape strings but not numbers to avoid MySQL complaining
141 if ( !is_int( $val ) && !is_float( $val ) ) {
142 $val = $this->addQuotes( $val );
143 }
144 $set[] = $this->platform->addIdentifierQuotes( $var ) . ' = ' . $val;
145 }
146 }
147
148 if ( $set ) {
149 $sql = 'SET ' . implode( ', ', $set );
150 $flags = self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX;
151 $query = new Query( $sql, $flags, 'SET' );
152 // Avoid using query() so that replaceLostConnection() does not throw
153 // errors if the transaction status is STATUS_TRX_ERROR
154 $qs = $this->executeQuery( $query, __METHOD__, $flags );
155 if ( $qs->res === false ) {
156 $this->reportQueryError( $qs->message, $qs->code, $sql, __METHOD__ );
157 }
158 }
159 } catch ( RuntimeException $e ) {
160 throw $this->newExceptionAfterConnectError( $e->getMessage() );
161 }
162 }
163
165 protected function doSelectDomain( DatabaseDomain $domain ) {
166 if ( $domain->getSchema() !== null ) {
167 throw new DBExpectedError(
168 $this,
169 __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
170 );
171 }
172
173 $database = $domain->getDatabase();
174 // A null database means "don't care" so leave it as is and update the table prefix
175 if ( $database === null ) {
176 $this->currentDomain = new DatabaseDomain(
177 $this->currentDomain->getDatabase(),
178 null,
179 $domain->getTablePrefix()
180 );
181 $this->platform->setCurrentDomain( $this->currentDomain );
182
183 return true;
184 }
185
186 if ( $database !== $this->getDBname() ) {
187 $sql = 'USE ' . $this->addIdentifierQuotes( $database );
188 $query = new Query( $sql, self::QUERY_CHANGE_TRX, 'USE' );
189 $qs = $this->executeQuery( $query, __METHOD__, self::QUERY_CHANGE_TRX );
190 if ( $qs->res === false ) {
191 $this->reportQueryError( $qs->message, $qs->code, $sql, __METHOD__ );
192 return false; // unreachable
193 }
194 }
195
196 // Update that domain fields on success (no exception thrown)
197 $this->currentDomain = $domain;
198 $this->platform->setCurrentDomain( $domain );
199
200 return true;
201 }
202
206 public function lastError() {
207 if ( $this->conn ) {
208 // Even if it's non-zero, it can still be invalid
209 $error = $this->mysqlError( $this->conn );
210 if ( !$error ) {
211 $error = $this->mysqlError();
212 }
213 } else {
214 $error = $this->mysqlError() ?: $this->lastConnectError;
215 }
216
217 return $error;
218 }
219
221 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions, $fname ) {
222 $row = $this->replicationReporter->getReplicationSafetyInfo( $this, $fname );
223 // For row-based-replication, the resulting changes will be relayed, not the query
224 if ( $row->binlog_format === 'ROW' ) {
225 return true;
226 }
227 // LIMIT requires ORDER BY on a unique key or it is non-deterministic
228 if ( isset( $selectOptions['LIMIT'] ) ) {
229 return false;
230 }
231 // In MySQL, an INSERT SELECT is only replication safe with row-based
232 // replication or if innodb_autoinc_lock_mode is 0. When those
233 // conditions aren't met, use non-native mode.
234 // While we could try to determine if the insert is safe anyway by
235 // checking if the target table has an auto-increment column that
236 // isn't set in $varMap, that seems unlikely to be worth the extra
237 // complexity.
238 return (
239 in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
240 (int)$row->innodb_autoinc_lock_mode === 0
241 );
242 }
243
245 protected function checkInsertWarnings( Query $query, $fname ) {
246 if ( $this->conn && $this->conn->warning_count ) {
247 // Yeah it's weird. It's not iterable.
248 $warnings = $this->conn->get_warnings();
249 $done = $warnings === false;
250 while ( !$done ) {
251 if ( in_array( $warnings->errno, [
252 // List based on https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#ignore-effect-on-execution
253 1048, /* ER_BAD_NULL_ERROR */
254 1526, /* ER_NO_PARTITION_FOR_GIVEN_VALUE */
255 1748, /* ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET */
256 1242, /* ER_SUBQUERY_NO_1_ROW */
257 1369, /* ER_VIEW_CHECK_FAILED */
258 // Truncation and overflow per T108255
259 1264, /* ER_WARN_DATA_OUT_OF_RANGE */
260 1265, /* WARN_DATA_TRUNCATED */
261 ] ) ) {
262 $this->reportQueryError(
263 'Insert returned unacceptable warning: ' . $warnings->message,
264 $warnings->errno,
265 $query->getSQL(),
266 $fname
267 );
268 }
269 $done = !$warnings->next();
270 }
271 }
272 }
273
275 public function estimateRowCount(
276 $tables,
277 $var = '*',
278 $conds = '',
279 $fname = __METHOD__,
280 $options = [],
281 $join_conds = []
282 ): int {
283 $conds = $this->platform->normalizeConditions( $conds, $fname );
284 $column = $this->platform->extractSingleFieldFromList( $var );
285 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
286 $conds[] = "$column IS NOT NULL";
287 }
288
289 $options['EXPLAIN'] = true;
290 $res = $this->select( $tables, $var, $conds, $fname, $options, $join_conds );
291 if ( $res === false ) {
292 return -1;
293 }
294 if ( !$res->numRows() ) {
295 return 0;
296 }
297
298 $rows = 1;
299 foreach ( $res as $plan ) {
300 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
301 }
302
303 return (int)$rows;
304 }
305
307 public function tableExists( $table, $fname = __METHOD__ ) {
308 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
309 if ( isset( $this->sessionTempTables[$db][$pt] ) ) {
310 return true; // already known to exist and won't be found in the query anyway
311 }
312
313 return (bool)$this->newSelectQueryBuilder()
314 ->select( '1' )
315 ->from( 'information_schema.tables' )
316 ->where( [
317 'table_schema' => $db,
318 'table_name' => $pt,
319 ] )
320 ->caller( $fname )
321 ->fetchField();
322 }
323
329 public function fieldInfo( $table, $field ) {
330 $query = new Query(
331 "SELECT * FROM " . $this->tableName( $table ) . " LIMIT 1",
332 self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
333 'SELECT'
334 );
335 $res = $this->query( $query, __METHOD__ );
336 if ( !$res ) {
337 return false;
338 }
340 '@phan-var MysqliResultWrapper $res';
341 return $res->getInternalFieldInfo( $field );
342 }
343
345 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
346 # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
347 $query = new Query(
348 'SHOW INDEX FROM ' . $this->tableName( $table ),
349 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
350 'SHOW'
351 );
352 $res = $this->query( $query, $fname );
353
354 foreach ( $res as $row ) {
355 if ( $row->Key_name === $index ) {
356 return [ 'unique' => !$row->Non_unique ];
357 }
358 }
359
360 return false;
361 }
362
364 public function getPrimaryKeyColumns( $table, $fname = __METHOD__ ) {
365 $query = new Query(
366 'SHOW INDEX FROM ' . $this->tableName( $table ),
367 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
368 'SHOW'
369 );
370 $res = $this->query( $query, $fname );
371
372 $bySeq = [];
373 foreach ( $res as $row ) {
374 if ( $row->Key_name === 'PRIMARY' ) {
375 $bySeq[(int)$row->Seq_in_index] = (string)$row->Column_name;
376 }
377 }
378
379 ksort( $bySeq );
380
381 return array_values( $bySeq );
382 }
383
388 public function strencode( $s ) {
389 return $this->mysqlRealEscapeString( $s );
390 }
391
393 public function serverIsReadOnly() {
394 // Avoid SHOW to avoid internal temporary tables
395 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
396 $query = new Query( "SELECT @@GLOBAL.read_only AS Value", $flags, 'SELECT' );
397 $res = $this->query( $query, __METHOD__ );
398 $row = $res->fetchObject();
399
400 return $row && $row->Value && $row->Value !== 'OFF';
401 }
402
406 public function getSoftwareLink() {
407 [ $variant ] = $this->getMySqlServerVariant();
408 if ( $variant === 'MariaDB' ) {
409 return '[{{int:version-db-mariadb-url}} MariaDB]';
410 }
411
412 return '[{{int:version-db-mysql-url}} MySQL]';
413 }
414
418 private function getMySqlServerVariant() {
419 $version = $this->getServerVersion();
420
421 // MariaDB includes its name in its version string; this is how MariaDB's version of
422 // the mysql command-line client identifies MariaDB servers.
423 // https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_version
424 // https://mariadb.com/kb/en/version/
425 $parts = explode( '-', $version, 2 );
426 $number = $parts[0];
427 $suffix = $parts[1] ?? '';
428 if ( str_contains( $suffix, 'MariaDB' ) || str_contains( $suffix, '-maria-' ) ) {
429 $vendor = 'MariaDB';
430 } else {
431 $vendor = 'MySQL';
432 }
433
434 return [ $vendor, $number ];
435 }
436
440 public function getServerVersion() {
441 // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
442 // it off (see RPL_VERSION_HACK in include/mysql_com.h).
443 $version = $this->conn->server_info;
444 if (
445 str_starts_with( $version, '5.5.5-' ) &&
446 ( str_contains( $version, 'MariaDB' ) || str_contains( $version, '-maria-' ) )
447 ) {
448 $version = substr( $version, strlen( '5.5.5-' ) );
449 }
450 return $version;
451 }
452
453 public function setSessionOptions( array $options ) {
454 $sqlAssignments = [];
455
456 if ( isset( $options['connTimeout'] ) ) {
457 $encTimeout = (int)$options['connTimeout'];
458 $sqlAssignments[] = "net_read_timeout=$encTimeout";
459 $sqlAssignments[] = "net_write_timeout=$encTimeout";
460 }
461 if ( isset( $options['groupConcatMaxLen'] ) ) {
462 $maxLength = (int)$options['groupConcatMaxLen'];
463 $sqlAssignments[] = "group_concat_max_len=$maxLength";
464 }
465
466 if ( $sqlAssignments ) {
467 $query = new Query(
468 'SET ' . implode( ', ', $sqlAssignments ),
469 self::QUERY_CHANGE_TRX | self::QUERY_CHANGE_NONE,
470 'SET'
471 );
472 $this->query( $query, __METHOD__ );
473 }
474 }
475
481 public function streamStatementEnd( &$sql, &$newLine ) {
482 if ( preg_match( '/^DELIMITER\s+(\S+)/i', $newLine, $m ) ) {
483 $this->delimiter = $m[1];
484 $newLine = '';
485 }
486
487 return parent::streamStatementEnd( $sql, $newLine );
488 }
489
491 public function doLock( string $lockName, string $method, int $timeout ) {
492 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
493 // Locks have no value during tests and can cause parallel tests to fail -- T427466
494 return parent::doLock( $lockName, $method, $timeout );
495 }
496 $query = new Query( $this->platform->lockSQLText( $lockName, $timeout ), self::QUERY_CHANGE_LOCKS, 'SELECT' );
497 $res = $this->query( $query, $method );
498 $row = $res->fetchObject();
499
500 return ( $row->acquired !== null ) ? (float)$row->acquired : null;
501 }
502
504 public function doUnlock( string $lockName, string $method ) {
505 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
506 return true;
507 }
508 $query = new Query( $this->platform->unlockSQLText( $lockName ), self::QUERY_CHANGE_LOCKS, 'SELECT' );
509 $res = $this->query( $query, $method );
510 $row = $res->fetchObject();
511
512 return ( $row->released == 1 );
513 }
514
516 protected function doFlushSession( $fname ) {
517 // Note that RELEASE_ALL_LOCKS() is not supported well enough to use here.
518 // https://mariadb.com/kb/en/release_all_locks/
519 $releaseLockFields = [];
520 foreach ( $this->sessionNamedLocks as $name => $info ) {
521 $encName = $this->addQuotes( $this->platform->makeLockName( $name ) );
522 $releaseLockFields[] = "RELEASE_LOCK($encName)";
523 }
524 if ( $releaseLockFields ) {
525 $sql = 'SELECT ' . implode( ',', $releaseLockFields );
526 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
527 $query = new Query( $sql, $flags, 'SELECT' );
528 $qs = $this->executeQuery( $query, __METHOD__, $flags );
529 if ( $qs->res === false ) {
530 $this->reportQueryError( $qs->message, $qs->code, $sql, $fname, true );
531 }
532 }
533 }
534
536 public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
537 $identityKey = $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
538 if ( !$rows ) {
539 return;
540 }
541 $this->platform->assertValidUpsertSetArray( $set, $identityKey, $rows );
542
543 $encTable = $this->tableName( $table );
544 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
545 $sqlColumnAssignments = $this->makeList( $set, self::LIST_SET );
546 // No need to expose __NEW.* since buildExcludedValue() uses VALUES(column)
547
548 // https://mariadb.com/kb/en/insert-on-duplicate-key-update/
549 // https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
550 $sql =
551 "INSERT INTO $encTable " .
552 "($sqlColumns) VALUES $sqlTuples " .
553 "ON DUPLICATE KEY UPDATE $sqlColumnAssignments";
554 $query = new Query( $sql, self::QUERY_CHANGE_ROWS, 'INSERT', $table );
555 $this->query( $query, $fname );
556 // Count updates of conflicting rows and row inserts equally toward the change count
557 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
558 }
559
561 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
562 $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
563 if ( !$rows ) {
564 return;
565 }
566 $encTable = $this->tableName( $table );
567 [ $sqlColumns, $sqlTuples ] = $this->platform->makeInsertLists( $rows );
568 // https://dev.mysql.com/doc/refman/8.0/en/replace.html
569 $sql = "REPLACE INTO $encTable ($sqlColumns) VALUES $sqlTuples";
570 // Note that any auto-increment columns on conflicting rows will be reassigned
571 // due to combined DELETE+INSERT semantics. This will be reflected in insertId().
572 $query = new Query( $sql, self::QUERY_CHANGE_ROWS, 'REPLACE', $table );
573 $this->query( $query, $fname );
574 // Do not count deletions of conflicting rows toward the change count
575 $this->lastQueryAffectedRows = min( $this->lastQueryAffectedRows, count( $rows ) );
576 }
577
579 protected function isConnectionError( $errno ) {
580 // https://mariadb.com/kb/en/mariadb-error-codes/
581 // https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html
582 // https://dev.mysql.com/doc/mysql-errors/8.0/en/client-error-reference.html
583 return in_array( $errno, [ 2013, 2006, 2003, 1927, 1053 ], true );
584 }
585
587 protected function isQueryTimeoutError( $errno ) {
588 // https://mariadb.com/kb/en/mariadb-error-codes/
589 // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
590 // https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html
591 // Note that 1969 is MariaDB specific and unused in MySQL.
592 return in_array( $errno, [ 3024, 1969, 1028 ], true );
593 }
594
596 protected function isKnownStatementRollbackError( $errno ) {
597 // https://mariadb.com/kb/en/mariadb-error-codes/
598 // https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html
599 return in_array(
600 $errno,
601 [ 3024, 1969, 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ],
602 true
603 );
604 }
605
613 public function duplicateTableStructure(
614 $oldName, $newName, $temporary = false, $fname = __METHOD__
615 ) {
616 $tmp = $temporary ? 'TEMPORARY ' : '';
617 $newNameQuoted = $this->addIdentifierQuotes( $newName );
618 $oldNameQuoted = $this->addIdentifierQuotes( $oldName );
619
620 $query = new Query(
621 "CREATE $tmp TABLE $newNameQuoted (LIKE $oldNameQuoted)",
622 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
623 $temporary ? 'CREATE TEMPORARY' : 'CREATE',
624 // Use a dot to avoid double-prefixing in Database::getTempTableWrites()
625 '.' . $newName
626 );
627 return $this->query( $query, $fname );
628 }
629
637 public function listTables( $prefix = null, $fname = __METHOD__ ) {
638 $qb = $this->newSelectQueryBuilder()
639 ->select( 'table_name' )
640 ->from( 'information_schema.tables' )
641 ->where( [
642 'table_schema' => $this->currentDomain->getDatabase(),
643 'table_type' => 'BASE TABLE'
644 ] )
645 ->caller( $fname );
646 if ( $prefix !== null && $prefix !== '' ) {
647 $qb->andWhere( $this->expr(
648 'table_name', IExpression::LIKE, new LikeValue( $prefix, $this->anyString() )
649 ) );
650 }
651 return $qb->fetchFieldValues();
652 }
653
655 public function selectSQLText(
656 $tables,
657 $vars,
658 $conds = '',
659 $fname = __METHOD__,
660 $options = [],
661 $join_conds = []
662 ) {
663 $sql = parent::selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds );
664 // https://dev.mysql.com/doc/refman/5.7/en/optimizer-hints.html
665 // https://mariadb.com/kb/en/library/aborting-statements/
666 $timeoutMsec = intval( $options['MAX_EXECUTION_TIME'] ?? 0 );
667 if ( $timeoutMsec > 0 ) {
668 [ $vendor, $number ] = $this->getMySqlServerVariant();
669 if ( $vendor === 'MariaDB' && version_compare( $number, '10.1.2', '>=' ) ) {
670 $timeoutSec = $timeoutMsec / 1000;
671 $sql = "SET STATEMENT max_statement_time=$timeoutSec FOR $sql";
672 } elseif ( $vendor === 'MySQL' && version_compare( $number, '5.7.0', '>=' ) ) {
673 $sql = preg_replace(
674 '/^SELECT(?=\s)/',
675 "SELECT /*+ MAX_EXECUTION_TIME($timeoutMsec)*/",
676 $sql
677 );
678 }
679 }
680
681 return $sql;
682 }
683
684 protected function doSingleStatementQuery( string $sql ): QueryStatus {
685 $conn = $this->getBindingHandle();
686
687 // Hide packet warnings caused by things like dropped connections
688 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
689 $res = @$conn->query( $sql );
690 // Note that mysqli::insert_id only reflects the last query statement
691 $insertId = (int)$conn->insert_id;
692 $this->lastQueryInsertId = $insertId;
693 $this->sessionLastAutoRowId = $insertId ?: $this->sessionLastAutoRowId;
694
695 return new QueryStatus(
696 $res instanceof mysqli_result ? new MysqliResultWrapper( $this, $res ) : $res,
697 $conn->affected_rows,
698 $conn->error,
699 $conn->errno
700 );
701 }
702
711 private function mysqlConnect( $server, $user, $password, $db ) {
712 if ( !function_exists( 'mysqli_init' ) ) {
713 throw $this->newExceptionAfterConnectError(
714 "MySQLi functions missing, have you compiled PHP with the --with-mysqli option?"
715 );
716 }
717
718 // PHP 8.1.0+ throws exceptions by default. Turn that off for consistency.
719 mysqli_report( MYSQLI_REPORT_OFF );
720
721 // Other than mysql_connect, mysqli_real_connect expects an explicit port number
722 // e.g. "localhost:1234" or "127.0.0.1:1234"
723 // or Unix domain socket path
724 // e.g. "localhost:/socket_path" or "localhost:/foo/bar:bar:bar"
725 // colons are known to be used by Google AppEngine,
726 // see <https://cloud.google.com/sql/docs/mysql/connect-app-engine>
727 //
728 // We need to parse the port or socket path out of $realServer
729 $port = null;
730 $socket = null;
731 $hostAndPort = IPUtils::splitHostAndPort( $server );
732 if ( $hostAndPort ) {
733 $realServer = $hostAndPort[0];
734 if ( $hostAndPort[1] ) {
735 $port = $hostAndPort[1];
736 }
737 } elseif ( substr_count( $server, ':/' ) == 1 ) {
738 // If we have a colon slash instead of a colon and a port number
739 // after the ip or hostname, assume it's the Unix domain socket path
740 [ $realServer, $socket ] = explode( ':', $server, 2 );
741 } else {
742 $realServer = $server;
743 }
744
745 $mysqli = mysqli_init();
746 // Make affectedRows() for UPDATE reflect the number of matching rows, regardless
747 // of whether any column values changed. This is what callers want to know and is
748 // consistent with what Postgres and SQLite return.
749 $flags = MYSQLI_CLIENT_FOUND_ROWS;
750 if ( $this->ssl ) {
751 $flags |= MYSQLI_CLIENT_SSL;
752 $mysqli->ssl_set(
753 $this->sslKeyPath,
754 $this->sslCertPath,
755 $this->sslCAFile,
756 $this->sslCAPath,
757 $this->sslCiphers
758 );
759 }
760 if ( $this->getFlag( self::DBO_COMPRESS ) ) {
761 $flags |= MYSQLI_CLIENT_COMPRESS;
762 }
763 if ( $this->getFlag( self::DBO_PERSISTENT ) ) {
764 $realServer = 'p:' . $realServer;
765 }
766
767 if ( $this->utf8Mode ) {
768 // Tell the server we're communicating with it in UTF-8.
769 // This may engage various charset conversions.
770 $mysqli->options( MYSQLI_SET_CHARSET_NAME, 'utf8' );
771 } else {
772 $mysqli->options( MYSQLI_SET_CHARSET_NAME, 'binary' );
773 }
774
775 $mysqli->options( MYSQLI_OPT_CONNECT_TIMEOUT, $this->connectTimeout ?: 3 );
776 if ( $this->receiveTimeout ) {
777 $mysqli->options( MYSQLI_OPT_READ_TIMEOUT, $this->receiveTimeout );
778 }
779
780 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal socket seems set when used
781 $ok = $mysqli->real_connect( $realServer, $user, $password, $db, $port, $socket, $flags );
782
783 return $ok ? $mysqli : null;
784 }
785
787 protected function closeConnection() {
788 return ( $this->conn instanceof mysqli ) ? mysqli_close( $this->conn ) : true;
789 }
790
792 protected function lastInsertId() {
793 return $this->sessionLastAutoRowId;
794 }
795
796 protected function doHandleSessionLossPreconnect() {
797 // https://mariadb.com/kb/en/last_insert_id/
798 $this->sessionLastAutoRowId = 0;
799 }
800
802 public function insertId() {
803 if ( $this->lastEmulatedInsertId === null ) {
804 $conn = $this->getBindingHandle();
805 // Note that mysqli::insert_id only reflects the last query statement
806 $this->lastEmulatedInsertId = (int)$conn->insert_id;
807 }
808
809 return $this->lastEmulatedInsertId;
810 }
811
815 public function lastErrno() {
816 if ( $this->conn instanceof mysqli ) {
817 return $this->conn->errno;
818 } else {
819 return mysqli_connect_errno();
820 }
821 }
822
827 private function mysqlError( $conn = null ) {
828 if ( $conn === null ) {
829 return (string)mysqli_connect_error();
830 } else {
831 return $conn->error;
832 }
833 }
834
838 private function mysqlRealEscapeString( $s ): string {
839 $conn = $this->getBindingHandle();
840
841 return $conn->real_escape_string( (string)$s );
842 }
843}
Base class for the more common types of database errors.
Class to handle database/schema/prefix specifications for IDatabase.
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.bool query}
upsert( $table, array $rows, $uniqueKeys, array $set, $fname=__METHOD__)
Upsert row(s) into a table, in the provided order, while updating conflicting rows....
isQueryTimeoutError( $errno)
Checks whether the cause of the error is detected to be a timeout.It returns false by default,...
getPrimaryKeyColumns( $table, $fname=__METHOD__)
Get the primary key columns of a table.to be used by updater onlystring[] query}
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
isKnownStatementRollbackError( $errno)
bool Whether it is known that the last query error only caused statement rollback This is for backwar...
insertId()
Get the sequence-based ID assigned by the last query method call.This method should only be called wh...
isConnectionError( $errno)
Do not use this method outside of Database/DBError classes.bool Whether the given query error was a c...
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.array<string,mixed>|false Index info map; false if it d...
isInsertSelectSafe(array $insertOptions, array $selectOptions, $fname)
bool Whether an INSERT SELECT with these options will be replication safe 1.31
doFlushSession( $fname)
Reset the server-side session state for named locks and table locks.Connection and query errors will ...
MysqlReplicationReporter $replicationReporter
checkInsertWarnings(Query $query, $fname)
Check for warnings after performing an INSERT query, and throw exceptions if necessary....
setSessionOptions(array $options)
Override database's default behavior.
doUnlock(string $lockName, string $method)
unlock()bool Success
__construct(array $params)
Additional $params include:
streamStatementEnd(&$sql, &$newLine)
doHandleSessionLossPreconnect()
Reset any additional subclass trx* and session* fields.
serverIsReadOnly()
bool Whether this DB server is running in server-side read-only mode query} 1.28
doSelectDomain(DatabaseDomain $domain)
1.32
estimateRowCount( $tables, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate the number of rows in dataset.MySQL allows you to estimate the number of rows that would be ...
lastInsertId()
Get a row ID from the last insert statement to implicitly assign one within the session....
selectSQLText( $tables, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Take the same arguments as IDatabase::select() and return the SQL it would use.This can be useful for...
replace( $table, $uniqueKeys, $rows, $fname=__METHOD__)
Insert row(s) into a table, in the provided order, while deleting conflicting rows....
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
closeConnection()
Closes underlying database connection.bool Whether connection was closed successfully 1....
doSingleStatementQuery(string $sql)
Run a query and return a QueryStatus instance with the query result information.
open( $server, $user, $password, $db, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)connectionParams} connectionParams} c...
doLock(string $lockName, string $method, int $timeout)
lock()float|null UNIX timestamp of lock acquisition; null on failure
A single concrete connection to a relational database.
Definition Database.php:38
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition Database.php:430
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.string
newExceptionAfterConnectError( $error)
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition Database.php:419
select( $tables, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.New callers should use newSe...
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.table, column, database) for use in a SQL queryDepending on the database...
executeQuery( $sql, $fname, $flags)
Execute a query without enforcing public (non-Database) caller restrictions.
Definition Database.php:666
close( $fname=__METHOD__)
Close the database connection.This should only be called after any transactions have been resolved,...
Definition Database.php:480
reportQueryError( $error, $errno, $sql, $fname, $ignore=false)
Report a query error.
if(is_string( $params['sqlMode'] ?? null)) $flags
Definition Database.php:213
getDBname()
Get the current database name; null if there isn't one.string|null
Content of like value.
Definition LikeValue.php:14
Holds information on Query to be executed.
Definition Query.php:17
const QUERY_CHANGE_TRX
Query is a Transaction Control Language command (BEGIN, USE, SET, ...)