1<?php 2/** 3 * This program is free software; you can redistribute it and/or modify 4 * it under the terms of the GNU General Public License as published by 5 * the Free Software Foundation; either version 2 of the License, or 6 * (at your option) any later version. 7 * 8 * This program is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License along 14 * with this program; if not, write to the Free Software Foundation, Inc., 15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 * http://www.gnu.org/copyleft/gpl.html 17 * 18 * @file 19 */ 20namespace Wikimedia\Rdbms; 21 22use Exception; 23use InvalidArgumentException; 24use stdClass; 25use Wikimedia\ScopedCallback; 26 27/** 28 * @defgroup Database Database 29 * This group deals with database interface functions 30 * and query specifics/optimisations. 31 */ 32/** 33 * Basic database interface for live and lazy-loaded relation database handles 34 * 35 * @note IDatabase and DBConnRef should be updated to reflect any changes 36 * @ingroup Database 37 */ 38interface IDatabase { 39 /** @var int Callback triggered immediately due to no active transaction */ 40 public const TRIGGER_IDLE = 1; 41 /** @var int Callback triggered by COMMIT */ 42 public const TRIGGER_COMMIT = 2; 43 /** @var int Callback triggered by ROLLBACK */ 44 public const TRIGGER_ROLLBACK = 3; 45 /** @var int Callback triggered by atomic section cancel (ROLLBACK TO SAVEPOINT) */ 46 public const TRIGGER_CANCEL = 4; 47 48 /** @var string Transaction is requested by regular caller outside of the DB layer */ 49 public const TRANSACTION_EXPLICIT = ''; 50 /** @var string Transaction is requested internally via DBO_TRX/startAtomic() */ 51 public const TRANSACTION_INTERNAL = 'implicit'; 52 53 /** @var string Atomic section is not cancelable */ 54 public const ATOMIC_NOT_CANCELABLE = ''; 55 /** @var string Atomic section is cancelable */ 56 public const ATOMIC_CANCELABLE = 'cancelable'; 57 58 /** @var string Commit/rollback is from outside the IDatabase handle and connection manager */ 59 public const FLUSHING_ONE = ''; 60 /** @var string Commit/rollback is from the connection manager for the IDatabase handle */ 61 public const FLUSHING_ALL_PEERS = 'flush'; 62 /** @var string Commit/rollback is from the IDatabase handle internally */ 63 public const FLUSHING_INTERNAL = 'flush-internal'; 64 65 /** @var string Do not remember the prior flags */ 66 public const REMEMBER_NOTHING = ''; 67 /** @var string Remember the prior flags */ 68 public const REMEMBER_PRIOR = 'remember'; 69 /** @var string Restore to the prior flag state */ 70 public const RESTORE_PRIOR = 'prior'; 71 /** @var string Restore to the initial flag state */ 72 public const RESTORE_INITIAL = 'initial'; 73 74 /** @var string Estimate total time (RTT, scanning, waiting on locks, applying) */ 75 public const ESTIMATE_TOTAL = 'total'; 76 /** @var string Estimate time to apply (scanning, applying) */ 77 public const ESTIMATE_DB_APPLY = 'apply'; 78 79 /** @var int Combine list with comma delimeters */ 80 public const LIST_COMMA = 0; 81 /** @var int Combine list with AND clauses */ 82 public const LIST_AND = 1; 83 /** @var int Convert map into a SET clause */ 84 public const LIST_SET = 2; 85 /** @var int Treat as field name and do not apply value escaping */ 86 public const LIST_NAMES = 3; 87 /** @var int Combine list with OR clauses */ 88 public const LIST_OR = 4; 89 90 /** @var int Enable debug logging of all SQL queries */ 91 public const DBO_DEBUG = 1; 92 /** @var int Unused since 1.34 */ 93 public const DBO_NOBUFFER = 2; 94 /** @var int Unused since 1.31 */ 95 public const DBO_IGNORE = 4; 96 /** @var int Automatically start a transaction before running a query if none is active */ 97 public const DBO_TRX = 8; 98 /** @var int Join load balancer transaction rounds (which control DBO_TRX) in non-CLI mode */ 99 public const DBO_DEFAULT = 16; 100 /** @var int Use DB persistent connections if possible */ 101 public const DBO_PERSISTENT = 32; 102 /** @var int DBA session mode; was used by Oracle */ 103 public const DBO_SYSDBA = 64; 104 /** @var int Schema file mode; was used by Oracle */ 105 public const DBO_DDLMODE = 128; 106 /** @var int Enable SSL/TLS in connection protocol */ 107 public const DBO_SSL = 256; 108 /** @var int Enable compression in connection protocol */ 109 public const DBO_COMPRESS = 512; 110 111 /** @var int Idiom for "no special flags" */ 112 public const QUERY_NORMAL = 0; 113 /** @var int Ignore query errors and return false when they happen */ 114 public const QUERY_SILENCE_ERRORS = 1; // b/c for 1.32 query() argument; (int)true = 1 115 /** 116 * @var int Treat the TEMPORARY table from the given CREATE query as if it is 117 * permanent as far as write tracking is concerned. This is useful for testing. 118 */ 119 public const QUERY_PSEUDO_PERMANENT = 2; 120 /** @var int Enforce that a query does not make effective writes */ 121 public const QUERY_REPLICA_ROLE = 4; 122 /** @var int Ignore the current presence of any DBO_TRX flag */ 123 public const QUERY_IGNORE_DBO_TRX = 8; 124 /** @var int Do not try to retry the query if the connection was lost */ 125 public const QUERY_NO_RETRY = 16; 126 /** @var int Query is known to be a read-only Data Query Language query */ 127 public const QUERY_CHANGE_NONE = 32; 128 /** @var int Query is known to be a Transaction Control Language command */ 129 public const QUERY_CHANGE_TRX = 64 | self::QUERY_IGNORE_DBO_TRX; 130 /** @var int Query is known to be a Data Manipulation Language command */ 131 public const QUERY_CHANGE_ROWS = 128; 132 /** @var int Query is known to be a Data Definition Language command */ 133 public const QUERY_CHANGE_SCHEMA = 256 | self::QUERY_IGNORE_DBO_TRX; 134 135 /** Flag to return the lock acquision timestamp (null if not acquired) */ 136 public const LOCK_TIMESTAMP = 1; 137 138 /** @var bool Parameter to unionQueries() for UNION ALL */ 139 public const UNION_ALL = true; 140 /** @var bool Parameter to unionQueries() for UNION DISTINCT */ 141 public const UNION_DISTINCT = false; 142 143 /** @var string Field for getLBInfo()/setLBInfo() */ 144 public const LB_TRX_ROUND_ID = 'trxRoundId'; 145 /** @var string Field for getLBInfo()/setLBInfo() */ 146 public const LB_READ_ONLY_REASON = 'readOnlyReason'; 147 148 /** @var string primary DB server than can stream OLTP updates to replica servers */ 149 public const ROLE_STREAMING_MASTER = 'streaming-master'; 150 /** @var string Replica server that streams OLTP updates from the primary DB server */ 151 public const ROLE_STREAMING_REPLICA = 'streaming-replica'; 152 /** @var string Replica server of a static dataset that does not get OLTP updates */ 153 public const ROLE_STATIC_CLONE = 'static-clone'; 154 /** @var string Unknown replication topology role */ 155 public const ROLE_UNKNOWN = 'unknown'; 156 157 /** @var string Unconditional update/delete of whole table */ 158 public const ALL_ROWS = '*'; 159 160 /** 161 * Get a human-readable string describing the current software version 162 * 163 * Use getServerVersion() to get machine-friendly information. 164 * 165 * @return string Version information from the database server 166 */ 167 public function getServerInfo(); 168 169 /** 170 * Get a non-recycled ID that uniquely identifies this server within the replication topology 171 * 172 * A replication topology defines which servers can originate changes to a given dataset 173 * and how those changes propagate among database servers. It is assumed that the server 174 * only participates in the replication of a single relevant dataset. 175 * 176 * @return string|null 32, 64, or 128 bit integer ID; null if not applicable or unknown 177 * @throws DBQueryError 178 * @since 1.37 179 */ 180 public function getTopologyBasedServerId(); 181 182 /** 183 * Get the replication topology role of this server 184 * 185 * A replication topology defines which servers can originate changes to a given dataset 186 * and how those changes propagate among database servers. It is assumed that the server 187 * only participates in the replication of a single relevant dataset. 188 * 189 * @return string One of the class ROLE_* constants 190 * @throws DBQueryError 191 * @since 1.34 192 */ 193 public function getTopologyRole(); 194 195 /** 196 * Get the readable name of the sole root primary DB server for the replication topology 197 * 198 * A replication topology defines which servers can originate changes to a given dataset 199 * and how those changes propagate among database servers. It is assumed that the server 200 * only participates in the replication of a single relevant dataset. 201 * 202 * @return string|null Readable server name; null if unknown or if co-primaries are defined 203 * @throws DBQueryError 204 * @since 1.37 205 */ 206 public function getTopologyRootPrimary(); 207 208 /** 209 * @deprecated since 1.37; use getTopologyRootPrimary() instead. 210 * @return string|null Readable server name; null if unknown or if co-primaries are defined 211 * @throws DBQueryError 212 * @since 1.34 213 */ 214 public function getTopologyRootMaster(); 215 216 /** 217 * Gets the current transaction level. 218 * 219 * Historically, transactions were allowed to be "nested". This is no 220 * longer supported, so this function really only returns a boolean. 221 * 222 * @return int The previous value 223 */ 224 public function trxLevel(); 225 226 /** 227 * Get the UNIX timestamp of the time that the transaction was established 228 * 229 * This can be used to reason about the staleness of SELECT data in REPEATABLE-READ 230 * transaction isolation level. Callers can assume that if a view-snapshot isolation 231 * is used, then the data read by SQL queries is *at least* up to date to that point 232 * (possibly more up-to-date since the first SELECT defines the snapshot). 233 * 234 * @return float|null Returns null if there is not active transaction 235 * @since 1.25 236 */ 237 public function trxTimestamp(); 238 239 /** 240 * @return bool Whether an explicit transaction or atomic sections are still open 241 * @since 1.28 242 */ 243 public function explicitTrxActive(); 244 245 /** 246 * Assert that all explicit transactions or atomic sections have been closed 247 * 248 * @throws DBTransactionError 249 * @since 1.32 250 */ 251 public function assertNoOpenTransactions(); 252 253 /** 254 * Get/set the table prefix 255 * 256 * @param string|null $prefix The table prefix to set, or omitted to leave it unchanged 257 * @return string The previous table prefix 258 */ 259 public function tablePrefix( $prefix = null ); 260 261 /** 262 * Get/set the db schema 263 * 264 * @param string|null $schema The database schema to set, or omitted to leave it unchanged 265 * @return string The previous db schema 266 */ 267 public function dbSchema( $schema = null ); 268 269 /** 270 * Get properties passed down from the server info array of the load balancer 271 * 272 * @param string|null $name The entry of the info array to get, or null to get the whole array 273 * @return array|mixed|null 274 */ 275 public function getLBInfo( $name = null ); 276 277 /** 278 * Set the entire array or a particular key of the managing load balancer info array 279 * 280 * Keys matching the IDatabase::LB_* constants are also used internally by subclasses 281 * 282 * @param array|string $nameOrArray The new array or the name of a key to set 283 * @param array|null $value If $nameOrArray is a string, the new key value (null to unset) 284 */ 285 public function setLBInfo( $nameOrArray, $value = null ); 286 287 /** 288 * Returns true if this database does an implicit order by when the column has an index 289 * For example: SELECT page_title FROM page LIMIT 1 290 * 291 * @return bool 292 */ 293 public function implicitOrderby(); 294 295 /** 296 * Get the last query that sent on account of IDatabase::query() 297 * 298 * @return string SQL text or empty string if there was no such query 299 */ 300 public function lastQuery(); 301 302 /** 303 * Get the last time the connection may have been used for a write query 304 * 305 * @return int|float UNIX timestamp or false 306 * @since 1.24 307 */ 308 public function lastDoneWrites(); 309 310 /** 311 * @return bool Whether there is a transaction open with possible write queries 312 * @since 1.27 313 */ 314 public function writesPending(); 315 316 /** 317 * @return bool Whether there is a transaction open with pre-commit callbacks pending 318 * @since 1.32 319 */ 320 public function preCommitCallbacksPending(); 321 322 /** 323 * Whether there is a transaction open with either possible write queries 324 * or unresolved pre-commit/commit/resolution callbacks pending 325 * 326 * This does *not* count recurring callbacks, e.g. from setTransactionListener(). 327 * 328 * @return bool 329 */ 330 public function writesOrCallbacksPending(); 331 332 /** 333 * Get the time spend running write queries for this transaction 334 * 335 * High values could be due to scanning, updates, locking, and such. 336 * 337 * @param string $type IDatabase::ESTIMATE_* constant [default: ESTIMATE_ALL] 338 * @return float|bool Returns false if not transaction is active 339 * @since 1.26 340 */ 341 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ); 342 343 /** 344 * Get the list of method names that did write queries for this transaction 345 * 346 * @return array 347 * @since 1.27 348 */ 349 public function pendingWriteCallers(); 350 351 /** 352 * Get the number of affected rows from pending write queries 353 * 354 * @return int 355 * @since 1.30 356 */ 357 public function pendingWriteRowsAffected(); 358 359 /** 360 * @return bool Whether a connection to the database open 361 */ 362 public function isOpen(); 363 364 /** 365 * Set a flag for this connection 366 * 367 * @param int $flag One of (IDatabase::DBO_DEBUG, IDatabase::DBO_TRX) 368 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING] 369 */ 370 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ); 371 372 /** 373 * Clear a flag for this connection 374 * 375 * @param int $flag One of (IDatabase::DBO_DEBUG, IDatabase::DBO_TRX) 376 * @param string $remember IDatabase::REMEMBER_* constant [default: REMEMBER_NOTHING] 377 */ 378 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ); 379 380 /** 381 * Restore the flags to their prior state before the last setFlag/clearFlag call 382 * 383 * @param string $state IDatabase::RESTORE_* constant. [default: RESTORE_PRIOR] 384 * @since 1.28 385 */ 386 public function restoreFlags( $state = self::RESTORE_PRIOR ); 387 388 /** 389 * Returns a boolean whether the flag $flag is set for this connection 390 * 391 * @param int $flag One of the class IDatabase::DBO_* constants 392 * @return bool 393 */ 394 public function getFlag( $flag ); 395 396 /** 397 * Return the currently selected domain ID 398 * 399 * Null components (database/schema) might change once a connection is established 400 * 401 * @return string 402 */ 403 public function getDomainID(); 404 405 /** 406 * Get the RDBMS type of the server (e.g. "mysql", "sqlite") 407 * 408 * @return string 409 */ 410 public function getType(); 411 412 /***************************************************************************/ 413 // region Deprecated IResultWrapper accessors 414 415 /** 416 * Fetch the next row from the given result object, in object form 417 * 418 * Fields can be retrieved with $row->fieldname, with fields acting like 419 * member variables. If no more rows are available, false is returned. 420 * 421 * @deprecated since 1.37 use IResultWrapper::fetchObject() 422 * 423 * @param IResultWrapper $res Object as returned from IDatabase::query(), etc. 424 * @return stdClass|bool 425 */ 426 public function fetchObject( IResultWrapper $res ); 427 428 /** 429 * Fetch the next row from the given result object, in associative array form 430 * 431 * Fields are retrieved with $row['fieldname']. 432 * If no more rows are available, false is returned. 433 * 434 * @deprecated since 1.37 use IResultWrapper::fetchRow() 435 * 436 * @param IResultWrapper $res Result object as returned from IDatabase::query(), etc. 437 * @return array|bool 438 */ 439 public function fetchRow( IResultWrapper $res ); 440 441 /** 442 * Get the number of rows in a query result 443 * 444 * Returns zero if the query did not return any rows or was a write query. 445 * 446 * @deprecated since 1.37 use IResultWrapper::numRows() 447 * 448 * @param IResultWrapper|bool $res A SQL result 449 * @return int 450 */ 451 public function numRows( $res ); 452 453 /** 454 * Get the number of fields in a result object 455 * @see https://www.php.net/mysql_num_fields 456 * 457 * @deprecated since 1.37 458 * 459 * @param IResultWrapper $res A SQL result 460 * @return int 461 */ 462 public function numFields( IResultWrapper $res ); 463 464 /** 465 * Get a field name in a result object 466 * @see https://www.php.net/mysql_field_name 467 * 468 * @deprecated since 1.37 469 * 470 * @param IResultWrapper $res A SQL result 471 * @param int $n 472 * @return string 473 */ 474 public function fieldName( IResultWrapper $res, $n ); 475 476 /** 477 * Free a result object returned by query() or select() 478 * 479 * It's usually not necessary to call this, just use unset() or let the variable 480 * holding the result object go out of scope. 481 * 482 * @deprecated since 1.37 Use IResultWrapper::free() 483 * 484 * @param IResultWrapper $res A SQL result 485 */ 486 public function freeResult( IResultWrapper $res ); 487 488 /** 489 * Change the position of the cursor in a result object 490 * @see https://www.php.net/mysql_data_seek 491 * 492 * @deprecated since 1.37 use IResultWrapper::seek() 493 * 494 * @param IResultWrapper $res A SQL result 495 * @param int $row 496 */ 497 public function dataSeek( IResultWrapper $res, $row ); 498 499 // endregion -- Deprecated IResultWrapper accessors 500 /***************************************************************************/ 501 502 /** 503 * Get the inserted value of an auto-increment row 504 * 505 * This should only be called after an insert that used an auto-incremented 506 * value. If no such insert was previously done in the current database 507 * session, the return value is undefined. 508 * 509 * @return int 510 */ 511 public function insertId(); 512 513 /** 514 * Get the last error number 515 * @see https://www.php.net/mysql_errno 516 * 517 * @return int 518 */ 519 public function lastErrno(); 520 521 /** 522 * Get a description of the last error 523 * @see https://www.php.net/mysql_error 524 * 525 * @return string 526 */ 527 public function lastError(); 528 529 /** 530 * Get the number of rows affected by the last write query. 531 * Similar to https://www.php.net/mysql_affected_rows but includes rows matched 532 * but not changed (ie. an UPDATE which sets all fields to the same value they already have). 533 * To get the old mysql_affected_rows behavior, include non-equality of the fields in WHERE. 534 * 535 * @return int 536 */ 537 public function affectedRows(); 538 539 /** 540 * Returns a wikitext style link to the DB's website (e.g. "[https://www.mysql.com/ MySQL]") 541 * 542 * Should at least contain plain text, if for some reason your database has no website. 543 * 544 * @return string Wikitext of a link to the server software's web site 545 */ 546 public function getSoftwareLink(); 547 548 /** 549 * A string describing the current software version, like from mysql_get_server_info() 550 * 551 * @return string Version information from the database server. 552 */ 553 public function getServerVersion(); 554 555 /** 556 * Close the database connection 557 * 558 * This should only be called after any transactions have been resolved, 559 * aside from read-only automatic transactions (assuming no callbacks are registered). 560 * If a transaction is still open anyway, it will be rolled back. 561 * 562 * @param string $fname Caller name 563 * @param int|null $owner ID of the calling instance (e.g. the LBFactory ID) 564 * @return bool Success 565 * @throws DBError 566 */ 567 public function close( $fname = __METHOD__, $owner = null ); 568 569 /** 570 * Run an SQL query and return the result 571 * 572 * If a connection loss is detected, then an attempt to reconnect will be made. 573 * For queries that involve no larger transactions or locks, they will be re-issued 574 * for convenience, provided the connection was re-established. 575 * 576 * In new code, the query wrappers select(), insert(), update(), delete(), 577 * etc. should be used where possible, since they give much better DBMS 578 * independence and automatically quote or validate user input in a variety 579 * of contexts. This function is generally only useful for queries which are 580 * explicitly DBMS-dependent and are unsupported by the query wrappers, such 581 * as CREATE TABLE. 582 * 583 * However, the query wrappers themselves should call this function. 584 * 585 * @param string $sql SQL query 586 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST 587 * comment (you can use __METHOD__ or add some extra info) 588 * @param int $flags Bit field of IDatabase::QUERY_* constants. Note that suppression 589 * of errors is best handled by try/catch rather than using one of these flags. 590 * @return bool|IResultWrapper True for a successful write query, IResultWrapper object 591 * for a successful read query, or false on failure if QUERY_SILENCE_ERRORS is set. 592 * @throws DBQueryError If the query is issued, fails, and QUERY_SILENCE_ERRORS is not set. 593 * @throws DBExpectedError If the query is not, and cannot, be issued yet (non-DBQueryError) 594 * @throws DBError If the query is inherently not allowed (non-DBExpectedError) 595 */ 596 public function query( $sql, $fname = __METHOD__, $flags = 0 ); 597 598 /** 599 * Create an empty SelectQueryBuilder which can be used to run queries 600 * against this connection. 601 * 602 * @return SelectQueryBuilder 603 */ 604 public function newSelectQueryBuilder(); 605 606 /** 607 * A SELECT wrapper which returns a single field from a single result row 608 * 609 * If no result rows are returned from the query, false is returned. 610 * 611 * @param string|array $table Table name. {@see select} for details. 612 * @param string|array $var The field name to select. This must be a valid SQL fragment: do not 613 * use unvalidated user input. Can be an array, but must contain exactly 1 element then. 614 * {@see select} for details. 615 * @param string|array $cond The condition array. {@see select} for details. 616 * @param string $fname The function name of the caller. 617 * @param string|array $options The query options. {@see select} for details. 618 * @param string|array $join_conds The query join conditions. {@see select} for details. 619 * @return mixed|false The value from the field, or false if nothing was found 620 * @throws DBError If an error occurs, {@see query} 621 */ 622 public function selectField( 623 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = [] 624 ); 625 626 /** 627 * A SELECT wrapper which returns a list of single field values from result rows 628 * 629 * If no result rows are returned from the query, an empty array is returned. 630 * 631 * @param string|array $table Table name. {@see select} for details. 632 * @param string $var The field name to select. This must be a valid SQL 633 * fragment: do not use unvalidated user input. 634 * @param string|array $cond The condition array. {@see select} for details. 635 * @param string $fname The function name of the caller. 636 * @param string|array $options The query options. {@see select} for details. 637 * @param string|array $join_conds The query join conditions. {@see select} for details. 638 * 639 * @return array The values from the field in the order they were returned from the DB 640 * @throws DBError If an error occurs, {@see query} 641 * @since 1.25 642 */ 643 public function selectFieldValues( 644 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = [] 645 ): array; 646 647 /** 648 * Execute a SELECT query constructed using the various parameters provided 649 * 650 * @param string|array $table Table name(s) 651 * 652 * May be either an array of table names, or a single string holding a table 653 * name. If an array is given, table aliases can be specified, for example: 654 * 655 * [ 'a' => 'user' ] 656 * 657 * This includes the user table in the query, with the alias "a" available 658 * for use in field names (e.g. a.user_name). 659 * 660 * A derived table, defined by the result of selectSQLText(), requires an alias 661 * key and a Subquery instance value which wraps the SQL query, for example: 662 * 663 * [ 'c' => new Subquery( 'SELECT ...' ) ] 664 * 665 * Joins using parentheses for grouping (since MediaWiki 1.31) may be 666 * constructed using nested arrays. For example, 667 * 668 * [ 'tableA', 'nestedB' => [ 'tableB', 'b2' => 'tableB2' ] ] 669 * 670 * along with `$join_conds` like 671 * 672 * [ 'b2' => [ 'JOIN', 'b_id = b2_id' ], 'nestedB' => [ 'LEFT JOIN', 'b_a = a_id' ] ] 673 * 674 * will produce SQL something like 675 * 676 * FROM tableA LEFT JOIN (tableB JOIN tableB2 AS b2 ON (b_id = b2_id)) ON (b_a = a_id) 677 * 678 * All of the table names given here are automatically run through 679 * Database::tableName(), which causes the table prefix (if any) to be 680 * added, and various other table name mappings to be performed. 681 * 682 * Do not use untrusted user input as a table name. Alias names should 683 * not have characters outside of the Basic multilingual plane. 684 * 685 * @param string|array $vars Field name(s) 686 * 687 * May be either a field name or an array of field names. The field names 688 * can be complete fragments of SQL, for direct inclusion into the SELECT 689 * query. If an array is given, field aliases can be specified, for example: 690 * 691 * [ 'maxrev' => 'MAX(rev_id)' ] 692 * 693 * This includes an expression with the alias "maxrev" in the query. 694 * 695 * If an expression is given, care must be taken to ensure that it is 696 * DBMS-independent. 697 * 698 * Untrusted user input must not be passed to this parameter. 699 * 700 * @param string|array $conds 701 * 702 * May be either a string containing a single condition, or an array of 703 * conditions. If an array is given, the conditions constructed from each 704 * element are combined with AND. 705 * 706 * Array elements may take one of two forms: 707 * 708 * - Elements with a numeric key are interpreted as raw SQL fragments. 709 * - Elements with a string key are interpreted as equality conditions, 710 * where the key is the field name. 711 * - If the value of such an array element is a scalar (such as a 712 * string), it will be treated as data and thus quoted appropriately. 713 * If it is null, an IS NULL clause will be added. 714 * - If the value is an array, an IN (...) clause will be constructed 715 * from its non-null elements, and an IS NULL clause will be added 716 * if null is present, such that the field may match any of the 717 * elements in the array. The non-null elements will be quoted. 718 * 719 * Note that expressions are often DBMS-dependent in their syntax. 720 * DBMS-independent wrappers are provided for constructing several types of 721 * expression commonly used in condition queries. See: 722 * - IDatabase::buildLike() 723 * - IDatabase::conditional() 724 * 725 * Untrusted user input is safe in the values of string keys, however untrusted 726 * input must not be used in the array key names or in the values of numeric keys. 727 * Escaping of untrusted input used in values of numeric keys should be done via 728 * IDatabase::addQuotes() 729 * 730 * Use an empty array, string, or IDatabase::ALL_ROWS to select all rows. 731 * 732 * You *can* put simple join conditions here, but this is strongly discouraged. 733 * Instead of 734 * 735 * // $conds... 736 * 'rev_actor = actor_id', 737 * 738 * use (see below for $join_conds): 739 * 740 * // $join_conds... 741 * 'actor' => [ 'JOIN', 'rev_actor = actor_id' ], 742 * 743 * @param string $fname Caller function name 744 * 745 * @param string|array $options Query options 746 * 747 * Optional: Array of query options. Boolean options are specified by 748 * including them in the array as a string value with a numeric key, for 749 * example: 750 * 751 * [ 'FOR UPDATE' ] 752 * 753 * The supported options are: 754 * 755 * - OFFSET: Skip this many rows at the start of the result set. OFFSET 756 * with LIMIT can theoretically be used for paging through a result set, 757 * but this is discouraged for performance reasons. 758 * 759 * - LIMIT: Integer: return at most this many rows. The rows are sorted 760 * and then the first rows are taken until the limit is reached. LIMIT 761 * is applied to a result set after OFFSET. 762 * 763 * - LOCK IN SHARE MODE: Boolean: lock the returned rows so that they can't be 764 * changed until the next COMMIT. Cannot be used with aggregate functions 765 * (COUNT, MAX, etc., but also DISTINCT). 766 * 767 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be 768 * changed nor read with LOCK IN SHARE MODE until the next COMMIT. 769 * Cannot be used with aggregate functions (COUNT, MAX, etc., but also DISTINCT). 770 * 771 * - DISTINCT: Boolean: return only unique result rows. 772 * 773 * - GROUP BY: May be either an SQL fragment string naming a field or 774 * expression to group by, or an array of such SQL fragments. 775 * 776 * - HAVING: May be either an string containing a HAVING clause or an array of 777 * conditions building the HAVING clause. If an array is given, the conditions 778 * constructed from each element are combined with AND. 779 * 780 * - ORDER BY: May be either an SQL fragment giving a field name or 781 * expression to order by, or an array of such SQL fragments. 782 * 783 * - USE INDEX: This may be either a string giving the index name to use 784 * for the query, or an array. If it is an associative array, each key 785 * gives the table name (or alias), each value gives the index name to 786 * use for that table. All strings are SQL fragments and so should be 787 * validated by the caller. 788 * 789 * - IGNORE INDEX: This may be either be a string giving an index name to 790 * ignore for the query, or an array. If it is an associative array, 791 * each key gives the table name (or alias), each value gives the index 792 * name to ignore for that table. All strings are SQL fragments and so 793 * should be validated by the caller. 794 * 795 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run, 796 * instead of SELECT. 797 * 798 * And also the following boolean MySQL extensions, see the MySQL manual 799 * for documentation: 800 * 801 * - STRAIGHT_JOIN 802 * - SQL_BIG_RESULT 803 * - SQL_BUFFER_RESULT 804 * - SQL_SMALL_RESULT 805 * - SQL_CALC_FOUND_ROWS 806 * 807 * @param string|array $join_conds Join conditions 808 * 809 * Optional associative array of table-specific join conditions. 810 * Simple conditions can also be specified in the regular $conds, 811 * but this is strongly discouraged in favor of the more explicit syntax here. 812 * 813 * The key of the array contains the table name or alias. The value is an 814 * array with two elements, numbered 0 and 1. The first gives the type of 815 * join, the second is the same as the $conds parameter. Thus it can be 816 * an SQL fragment, or an array where the string keys are equality and the 817 * numeric keys are SQL fragments all AND'd together. For example: 818 * 819 * [ 'page' => [ 'LEFT JOIN', 'page_latest=rev_id' ] ] 820 * 821 * @return IResultWrapper Resulting rows 822 * @throws DBError If an error occurs, {@see query} 823 */ 824 public function select( 825 $table, 826 $vars, 827 $conds = '', 828 $fname = __METHOD__, 829 $options = [], 830 $join_conds = [] 831 ); 832 833 /** 834 * Take the same arguments as IDatabase::select() and return the SQL it would use 835 * 836 * This can be useful for making UNION queries, where the SQL text of each query 837 * is needed. In general, however, callers outside of Database classes should just 838 * use select(). 839 * 840 * @see IDatabase::select() 841 * 842 * @param string|array $table Table name 843 * @param string|array $vars Field names 844 * @param string|array $conds Conditions 845 * @param string $fname Caller function name 846 * @param string|array $options Query options 847 * @param string|array $join_conds Join conditions 848 * @return string SQL query string 849 */ 850 public function selectSQLText( 851 $table, 852 $vars, 853 $conds = '', 854 $fname = __METHOD__, 855 $options = [], 856 $join_conds = [] 857 ); 858 859 /** 860 * Wrapper to IDatabase::select() that only fetches one row (via LIMIT) 861 * 862 * If the query returns no rows, false is returned. 863 * 864 * This method is convenient for fetching a row based on a unique key condition. 865 * 866 * @param string|array $table Table name 867 * @param string|array $vars Field names 868 * @param string|array $conds Conditions 869 * @param string $fname Caller function name 870 * @param string|array $options Query options 871 * @param array|string $join_conds Join conditions 872 * @return stdClass|bool 873 * @throws DBError If an error occurs, {@see query} 874 */ 875 public function selectRow( 876 $table, 877 $vars, 878 $conds, 879 $fname = __METHOD__, 880 $options = [], 881 $join_conds = [] 882 ); 883 884 /** 885 * Estimate the number of rows in dataset 886 * 887 * MySQL allows you to estimate the number of rows that would be returned 888 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using 889 * index cardinality statistics, and is notoriously inaccurate, especially 890 * when large numbers of rows have recently been added or deleted. 891 * 892 * For DBMSs that don't support fast result size estimation, this function 893 * will actually perform the SELECT COUNT(*). 894 * 895 * Takes the same arguments as IDatabase::select(). 896 * 897 * @param string|string[] $tables Table name(s) 898 * @param string $var Column for which NULL values are not counted [default "*"] 899 * @param array|string $conds Filters on the table 900 * @param string $fname Function name for profiling 901 * @param array $options Options for select 902 * @param array|string $join_conds Join conditions 903 * @return int Row count 904 * @throws DBError If an error occurs, {@see query} 905 */ 906 public function estimateRowCount( 907 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = [] 908 ); 909 910 /** 911 * Get the number of rows in dataset 912 * 913 * This is useful when trying to do COUNT(*) but with a LIMIT for performance. 914 * 915 * Takes the same arguments as IDatabase::select(). 916 * 917 * @since 1.27 Added $join_conds parameter 918 * 919 * @param string|string[] $tables Table name(s) 920 * @param string $var Column for which NULL values are not counted [default "*"] 921 * @param array|string $conds Filters on the table 922 * @param string $fname Function name for profiling 923 * @param array $options Options for select 924 * @param array $join_conds Join conditions (since 1.27) 925 * @return int Row count 926 * @throws DBError If an error occurs, {@see query} 927 */ 928 public function selectRowCount( 929 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = [] 930 ); 931 932 /** 933 * Lock all rows meeting the given conditions/options FOR UPDATE 934 * 935 * @param string|string[] $table Table name(s) 936 * @param array|string $conds Filters on the table 937 * @param string $fname Function name for profiling 938 * @param array $options Options for select ("FOR UPDATE" is added automatically) 939 * @param array $join_conds Join conditions 940 * @return int Number of matching rows found (and locked) 941 * @throws DBError If an error occurs, {@see query} 942 * @since 1.32 943 */ 944 public function lockForUpdate( 945 $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = [] 946 ); 947 948 /** 949 * Determines whether a field exists in a table 950 * 951 * @param string $table Table name 952 * @param string $field Filed to check on that table 953 * @param string $fname Calling function name (optional) 954 * @return bool Whether $table has filed $field 955 * @throws DBError If an error occurs, {@see query} 956 */ 957 public function fieldExists( $table, $field, $fname = __METHOD__ ); 958 959 /** 960 * Determines whether an index exists 961 * 962 * @param string $table 963 * @param string $index 964 * @param string $fname 965 * @return bool|null 966 * @throws DBError If an error occurs, {@see query} 967 */ 968 public function indexExists( $table, $index, $fname = __METHOD__ ); 969 970 /** 971 * Query whether a given table exists 972 * 973 * @param string $table 974 * @param string $fname 975 * @return bool 976 * @throws DBError If an error occurs, {@see query} 977 */ 978 public function tableExists( $table, $fname = __METHOD__ ); 979 980 /** 981 * Insert the given row(s) into a table 982 * 983 * @param string $table Table name 984 * @param array|array[] $rows Row(s) to insert, as either: 985 * - A string-keyed map of (column name => value) defining a new row. Values are 986 * treated as literals and quoted appropriately; null is interpreted as NULL. 987 * - An integer-keyed list of such string-keyed maps, defining a list of new rows. 988 * The keys in each map must be identical to each other and in the same order. 989 * The rows must not collide with each other. 990 * @param string $fname Calling function name (use __METHOD__) for logs/profiling 991 * @param string|array $options Combination map/list where each string-keyed entry maps 992 * a non-boolean option to the option parameters and each integer-keyed value is the 993 * name of a boolean option. Supported options are: 994 * - IGNORE: Boolean: skip insertion of rows that would cause unique key conflicts. 995 * IDatabase::affectedRows() can be used to determine how many rows were inserted. 996 * @return bool Return true if no exception was thrown (deprecated since 1.33) 997 * @throws DBError If an error occurs, {@see query} 998 */ 999 public function insert( $table, $rows, $fname = __METHOD__, $options = [] ); 1000 1001 /** 1002 * Update all rows in a table that match a given condition 1003 * 1004 * @param string $table Table name 1005 * @param array $set Combination map/list where each string-keyed entry maps a column 1006 * to a literal assigned value and each integer-keyed value is a SQL expression in the 1007 * format of a column assignment within UPDATE...SET. The (column => value) entries are 1008 * convenient due to automatic value quoting and conversion of null to NULL. The SQL 1009 * assignment format is useful for updates like "column = column + X". All assignments 1010 * have no defined execution order, so they should not depend on each other. Do not 1011 * modify AUTOINCREMENT or UUID columns in assignments. 1012 * @param array|string $conds Condition in the format of IDatabase::select() conditions. 1013 * In order to prevent possible performance or replication issues or damaging a data 1014 * accidentally, an empty condition for 'update' queries isn't allowed. 1015 * IDatabase::ALL_ROWS should be passed explicitely in order to update all rows. 1016 * @param string $fname Calling function name (use __METHOD__) for logs/profiling 1017 * @param string|array $options Combination map/list where each string-keyed entry maps 1018 * a non-boolean option to the option parameters and each integer-keyed value is the 1019 * name of a boolean option. Supported options are: 1020 * - IGNORE: Boolean: skip update of rows that would cause unique key conflicts. 1021 * IDatabase::affectedRows() can be used to determine how many rows were updated. 1022 * @return bool Return true if no exception was thrown (deprecated since 1.33) 1023 * @throws DBError If an error occurs, {@see query} 1024 */ 1025 public function update( $table, $set, $conds, $fname = __METHOD__, $options = [] ); 1026 1027 /** 1028 * Makes an encoded list of strings from an array 1029 * 1030 * These can be used to make conjunctions or disjunctions on SQL condition strings 1031 * derived from an array ({@see select} $conds documentation). 1032 * 1033 * Example usage: 1034 * @code 1035 * $sql = $db->makeList( [ 1036 * 'rev_page' => $id, 1037 * $db->makeList( [ 'rev_minor' => 1, 'rev_len' < 500 ], $db::LIST_OR ] ) 1038 * ], $db::LIST_AND ); 1039 * @endcode 1040 * This would set $sql to "rev_page = '$id' AND (rev_minor = '1' OR rev_len < '500')" 1041 * 1042 * @param array $a Containing the data 1043 * @param int $mode IDatabase class constant: 1044 * - IDatabase::LIST_COMMA: Comma separated, no field names 1045 * - IDatabase::LIST_AND: ANDed WHERE clause (without the WHERE). 1046 * - IDatabase::LIST_OR: ORed WHERE clause (without the WHERE) 1047 * - IDatabase::LIST_SET: Comma separated with field names, like a SET clause 1048 * - IDatabase::LIST_NAMES: Comma separated field names 1049 * @throws DBError If an error occurs, {@see query} 1050 * @return string 1051 */ 1052 public function makeList( array $a, $mode = self::LIST_COMMA ); 1053 1054 /** 1055 * Build a partial where clause from a 2-d array such as used for LinkBatch. 1056 * 1057 * The keys on each level may be either integers or strings, however it's 1058 * assumed that $baseKey is probably an integer-typed column (i.e. integer 1059 * keys are unquoted in the SQL) and $subKey is string-typed (i.e. integer 1060 * keys are quoted as strings in the SQL). 1061 * 1062 * @todo Does this actually belong in the library? It seems overly MW-specific. 1063 * 1064 * @param array $data Organized as 2-d 1065 * [ baseKeyVal => [ subKeyVal => [ignored], ... ], ... ] 1066 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace') 1067 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title') 1068 * @return string|bool SQL fragment, or false if no items in array 1069 */ 1070 public function makeWhereFrom2d( $data, $baseKey, $subKey ); 1071 1072 /** 1073 * Return aggregated value alias 1074 * 1075 * @param array $valuedata 1076 * @param string $valuename 1077 * 1078 * @return array|string 1079 * @deprecated Since 1.33 1080 */ 1081 public function aggregateValue( $valuedata, $valuename = 'value' ); 1082 1083 /** 1084 * @param string|int $field 1085 * @return string 1086 */ 1087 public function bitNot( $field ); 1088 1089 /** 1090 * @param string|int $fieldLeft 1091 * @param string|int $fieldRight 1092 * @return string 1093 */ 1094 public function bitAnd( $fieldLeft, $fieldRight ); 1095 1096 /** 1097 * @param string|int $fieldLeft 1098 * @param string|int $fieldRight 1099 * @return string 1100 */ 1101 public function bitOr( $fieldLeft, $fieldRight ); 1102 1103 /** 1104 * Build a concatenation list to feed into a SQL query 1105 * @param string[] $stringList Raw SQL expression list; caller is responsible for escaping 1106 * @return string 1107 */ 1108 public function buildConcat( $stringList ); 1109 1110 /** 1111 * Build a GROUP_CONCAT or equivalent statement for a query. 1112 * 1113 * This is useful for combining a field for several rows into a single string. 1114 * NULL values will not appear in the output, duplicated values will appear, 1115 * and the resulting delimiter-separated values have no defined sort order. 1116 * Code using the results may need to use the PHP unique() or sort() methods. 1117 * 1118 * @param string $delim Glue to bind the results together 1119 * @param string|array $table Table name 1120 * @param string $field Field name 1121 * @param string|array $conds Conditions 1122 * @param string|array $join_conds Join conditions 1123 * @return string SQL text 1124 * @since 1.23 1125 */ 1126 public function buildGroupConcatField( 1127 $delim, $table, $field, $conds = '', $join_conds = [] 1128 ); 1129 1130 /** 1131 * Build a GREATEST function statement comparing columns/values 1132 * 1133 * Integer and float values in $values will not be quoted 1134 * 1135 * If $fields is an array, then each value with a string key is treated as an expression 1136 * (which must be manually quoted); such string keys do not appear in the SQL and are only 1137 * descriptive aliases. 1138 * 1139 * @param string|string[] $fields Name(s) of column(s) with values to compare 1140 * @param string|int|float|string[]|int[]|float[] $values Values to compare 1141 * @return mixed 1142 * @since 1.35 1143 */ 1144 public function buildGreatest( $fields, $values ); 1145 1146 /** 1147 * Build a LEAST function statement comparing columns/values 1148 * 1149 * Integer and float values in $values will not be quoted 1150 * 1151 * If $fields is an array, then each value with a string key is treated as an expression 1152 * (which must be manually quoted); such string keys do not appear in the SQL and are only 1153 * descriptive aliases. 1154 * 1155 * @param string|string[] $fields Name(s) of column(s) with values to compare 1156 * @param string|int|float|string[]|int[]|float[] $values Values to compare 1157 * @return mixed 1158 * @since 1.35 1159 */ 1160 public function buildLeast( $fields, $values ); 1161 1162 /** 1163 * Build a SUBSTRING function 1164 * 1165 * Behavior for non-ASCII values is undefined. 1166 * 1167 * @param string $input Field name 1168 * @param int $startPosition Positive integer 1169 * @param int|null $length Non-negative integer length or null for no limit 1170 * @throws InvalidArgumentException 1171 * @return string SQL text 1172 * @since 1.31 1173 */ 1174 public function buildSubString( $input, $startPosition, $length = null ); 1175 1176 /** 1177 * @param string $field Field or column to cast 1178 * @return string 1179 * @since 1.28 1180 */ 1181 public function buildStringCast( $field ); 1182 1183 /** 1184 * @param string $field Field or column to cast 1185 * @return string 1186 * @since 1.31 1187 */ 1188 public function buildIntegerCast( $field ); 1189 1190 /** 1191 * Equivalent to IDatabase::selectSQLText() except wraps the result in Subquery 1192 * 1193 * @see IDatabase::selectSQLText() 1194 * 1195 * @param string|array $table Table name 1196 * @param string|array $vars Field names 1197 * @param string|array $conds Conditions 1198 * @param string $fname Caller function name 1199 * @param string|array $options Query options 1200 * @param string|array $join_conds Join conditions 1201 * @return Subquery 1202 * @since 1.31 1203 */ 1204 public function buildSelectSubquery( 1205 $table, 1206 $vars, 1207 $conds = '', 1208 $fname = __METHOD__, 1209 $options = [], 1210 $join_conds = [] 1211 ); 1212 1213 /** 1214 * Construct a LIMIT query with optional offset 1215 * 1216 * The SQL should be adjusted so that only the first $limit rows 1217 * are returned. If $offset is provided as well, then the first $offset 1218 * rows should be discarded, and the next $limit rows should be returned. 1219 * If the result of the query is not ordered, then the rows to be returned 1220 * are theoretically arbitrary. 1221 * 1222 * $sql is expected to be a SELECT, if that makes a difference. 1223 * 1224 * @param string $sql SQL query we will append the limit too 1225 * @param int $limit The SQL limit 1226 * @param int|bool $offset The SQL offset (default false) 1227 * @return string 1228 * @since 1.34 1229 */ 1230 public function limitResult( $sql, $limit, $offset = false ); 1231 1232 /** 1233 * Returns true if DBs are assumed to be on potentially different servers 1234 * 1235 * In systems like mysql/mariadb, different databases can easily be referenced on a single 1236 * connection merely by name, even in a single query via JOIN. On the other hand, Postgres 1237 * treats databases as logically separate, with different database users, requiring special 1238 * mechanisms like postgres_fdw to "mount" foreign DBs. This is true even among DBs on the 1239 * same server. Changing the selected database via selectDomain() requires a new connection. 1240 * 1241 * @return bool 1242 * @since 1.29 1243 */ 1244 public function databasesAreIndependent(); 1245 1246 /** 1247 * Change the current database 1248 * 1249 * This should only be called by a load balancer or if the handle is not attached to one 1250 * 1251 * @param string $db 1252 * @return bool True unless an exception was thrown 1253 * @throws DBConnectionError If databasesAreIndependent() is true and connection change fails 1254 * @throws DBError On query error or if database changes are disallowed 1255 * @deprecated Since 1.32 Use selectDomain() instead 1256 */ 1257 public function selectDB( $db ); 1258 1259 /** 1260 * Set the current domain (database, schema, and table prefix) 1261 * 1262 * This will throw an error for some database types if the database is unspecified 1263 * 1264 * This should only be called by a load balancer or if the handle is not attached to one 1265 * 1266 * @param string|DatabaseDomain $domain 1267 * @throws DBConnectionError If databasesAreIndependent() is true and connection change fails 1268 * @throws DBError On query error, if domain changes are disallowed, or the domain is invalid 1269 * @since 1.32 1270 */ 1271 public function selectDomain( $domain ); 1272 1273 /** 1274 * Get the current database name; null if there isn't one 1275 * 1276 * @return string|null 1277 */ 1278 public function getDBname(); 1279 1280 /** 1281 * Get the hostname or IP address of the server 1282 * 1283 * @return string|null 1284 */ 1285 public function getServer(); 1286 1287 /** 1288 * Get the readable name for the server 1289 * 1290 * @return string Readable server name, falling back to the hostname or IP address 1291 * @since 1.36 1292 */ 1293 public function getServerName(); 1294 1295 /** 1296 * Escape and quote a raw value string for use in a SQL query 1297 * 1298 * @param string|int|float|null|bool|Blob $s 1299 * @return string 1300 */ 1301 public function addQuotes( $s ); 1302 1303 /** 1304 * Escape a SQL identifier (e.g. table, column, database) for use in a SQL query 1305 * 1306 * Depending on the database this will either be `backticks` or "double quotes" 1307 * 1308 * @param string $s 1309 * @return string 1310 * @since 1.33 1311 */ 1312 public function addIdentifierQuotes( $s ); 1313 1314 /** 1315 * LIKE statement wrapper 1316 * 1317 * This takes a variable-length argument list with parts of pattern to match 1318 * containing either string literals that will be escaped or tokens returned by 1319 * anyChar() or anyString(). Alternatively, the function could be provided with 1320 * an array of aforementioned parameters. 1321 * 1322 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns 1323 * a LIKE clause that searches for subpages of 'My page title'. 1324 * Alternatively: 1325 * $pattern = [ 'My_page_title/', $dbr->anyString() ]; 1326 * $query .= $dbr->buildLike( $pattern ); 1327 * 1328 * @since 1.16 1329 * @param array[]|string|LikeMatch $param 1330 * @param string|LikeMatch ...$params 1331 * @return string Fully built LIKE statement 1332 */ 1333 public function buildLike( $param, ...$params ); 1334 1335 /** 1336 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query 1337 * 1338 * @return LikeMatch 1339 */ 1340 public function anyChar(); 1341 1342 /** 1343 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query 1344 * 1345 * @return LikeMatch 1346 */ 1347 public function anyString(); 1348 1349 /** 1350 * Deprecated method, calls should be removed 1351 * 1352 * This was formerly used for PostgreSQL to handle 1353 * self::insertId() auto-incrementing fields. It is no longer necessary 1354 * since DatabasePostgres::insertId() has been reimplemented using 1355 * `lastval()` 1356 * 1357 * Implementations should return null if inserting `NULL` into an 1358 * auto-incrementing field works, otherwise it should return an instance of 1359 * NextSequenceValue and filter it on calls to relevant methods. 1360 * 1361 * @deprecated since 1.30, no longer needed 1362 * @param string $seqName 1363 * @return null|NextSequenceValue 1364 */ 1365 public function nextSequenceValue( $seqName ); 1366 1367 /** 1368 * Insert row(s) into a table, deleting all conflicting rows beforehand 1369 * 1370 * Note some important implications of the deletion semantics: 1371 * - If the table has an AUTOINCREMENT column and $rows omit that column, then any 1372 * conflicting existing rows will be replaced with newer having higher values for 1373 * that column, even if nothing else changed. 1374 * - There might be worse contention than upsert() due to the use of gap-locking. 1375 * This does not apply to RDBMS types that use predicate locking nor those that 1376 * just lock the whole table or databases anyway. 1377 * 1378 * @param string $table The table name 1379 * @param string|string[]|string[][] $uniqueKeys Column name or non-empty list of column 1380 * name lists that define all applicable unique keys on the table. There must only be 1381 * one such key. Each unique key on the table is "applicable" unless either: 1382 * - It involves an AUTOINCREMENT column for which no values are assigned in $rows 1383 * - It involves a UUID column for which newly generated UUIDs are assigned in $rows 1384 * @param array|array[] $rows Row(s) to insert, in the form of either: 1385 * - A string-keyed map of (column name => value) defining a new row. Values are 1386 * treated as literals and quoted appropriately; null is interpreted as NULL. 1387 * Columns belonging to a key in $uniqueKeys must be defined here and non-null. 1388 * - An integer-keyed list of such string-keyed maps, defining a list of new rows. 1389 * The keys in each map must be identical to each other and in the same order. 1390 * The rows must not collide with each other. 1391 * @param string $fname Calling function name (use __METHOD__) for logs/profiling 1392 * @throws DBError If an error occurs, {@see query} 1393 */ 1394 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ); 1395 1396 /** 1397 * Upsert the given row(s) into a table 1398 * 1399 * This updates any existing rows that conflict with the provided rows and inserts 1400 * any of the provided rows that do not conflict with existing rows. Conflicts are 1401 * determined by the provided unique indexes. 1402 * 1403 * @param string $table Table name 1404 * @param array|array[] $rows Row(s) to insert, in the form of either: 1405 * - A string-keyed map of (column name => value) defining a new row. Values are 1406 * treated as literals and quoted appropriately; null is interpreted as NULL. 1407 * Columns belonging to a key in $uniqueKeys must be defined here and non-null. 1408 * - An integer-keyed list of such string-keyed maps, defining a list of new rows. 1409 * The keys in each map must be identical to each other and in the same order. 1410 * The rows must not collide with each other. 1411 * @param string|string[]|string[][] $uniqueKeys Column name or non-empty list of column 1412 * name lists that define all applicable unique keys on the table. There must only be 1413 * one such key. Each unique key on the table is "applicable" unless either: 1414 * - It involves an AUTOINCREMENT column for which no values are assigned in $rows 1415 * - It involves a UUID column for which newly generated UUIDs are assigned in $rows 1416 * Passing string[] to $uniqueKeys is deprecated. 1417 * @param array $set Combination map/list where each string-keyed entry maps a column 1418 * to a literal assigned value and each integer-keyed value is a SQL assignment expression 1419 * of the form "<unquoted alphanumeric column> = <SQL expression>". The (column => value) 1420 * entries are convenient due to automatic value quoting and conversion of null to NULL. 1421 * The SQL assignment entries are useful for updates like "column = column + X". All of 1422 * the assignments have no defined execution order, so callers should make sure that they 1423 * not depend on each other. Do not modify AUTOINCREMENT or UUID columns in assignments, 1424 * even if they are just "secondary" unique keys. 1425 * @param string $fname Calling function name (use __METHOD__) for logs/profiling 1426 * @return bool Return true if no exception was thrown (deprecated since 1.33) 1427 * @throws DBError If an error occurs, {@see query} 1428 * @since 1.22 1429 */ 1430 public function upsert( 1431 $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ 1432 ); 1433 1434 /** 1435 * DELETE where the condition is a join. 1436 * 1437 * MySQL overrides this to use a multi-table DELETE syntax, in other databases 1438 * we use sub-selects 1439 * 1440 * For safety, an empty $conds will not delete everything. If you want to 1441 * delete all rows where the join condition matches, set $conds=IDatabase::ALL_ROWS. 1442 * 1443 * DO NOT put the join condition in $conds. 1444 * 1445 * @param string $delTable The table to delete from. 1446 * @param string $joinTable The other table. 1447 * @param string $delVar The variable to join on, in the first table. 1448 * @param string $joinVar The variable to join on, in the second table. 1449 * @param array|string $conds Condition array of field names mapped to variables, 1450 * ANDed together in the WHERE clause 1451 * @param string $fname Calling function name (use __METHOD__) for logs/profiling 1452 * @throws DBError If an error occurs, {@see query} 1453 */ 1454 public function deleteJoin( 1455 $delTable, 1456 $joinTable, 1457 $delVar, 1458 $joinVar, 1459 $conds, 1460 $fname = __METHOD__ 1461 ); 1462 1463 /** 1464 * Delete all rows in a table that match a condition 1465 * 1466 * @param string $table Table name 1467 * @param string|array $conds Array of conditions. See $conds in IDatabase::select() 1468 * In order to prevent possible performance or replication issues or damaging a data 1469 * accidentally, an empty condition for 'delete' queries isn't allowed. 1470 * IDatabase::ALL_ROWS should be passed explicitely in order to delete all rows. 1471 * @param string $fname Name of the calling function 1472 * @return bool Return true if no exception was thrown (deprecated since 1.33) 1473 * @throws DBError If an error occurs, {@see query} 1474 */ 1475 public function delete( $table, $conds, $fname = __METHOD__ ); 1476 1477 /** 1478 * INSERT SELECT wrapper 1479 * 1480 * @warning If the insert will use an auto-increment or sequence to 1481 * determine the value of a column, this may break replication on 1482 * databases using statement-based replication if the SELECT is not 1483 * deterministically ordered. 1484 * 1485 * @param string $destTable The table name to insert into 1486 * @param string|array $srcTable May be either a table name, or an array of table names 1487 * to include in a join. 1488 * @param array $varMap Must be an associative array of the form 1489 * [ 'dest1' => 'source1', ... ]. Source items may be literals 1490 * rather than field names, but strings should be quoted with 1491 * IDatabase::addQuotes() 1492 * @param array $conds Condition array. See $conds in IDatabase::select() for 1493 * the details of the format of condition arrays. May be "*" to copy the 1494 * whole table. 1495 * @param string $fname The function name of the caller, from __METHOD__ 1496 * @param array $insertOptions Options for the INSERT part of the query, see 1497 * IDatabase::insert() for details. Also, one additional option is 1498 * available: pass 'NO_AUTO_COLUMNS' to hint that the query does not use 1499 * an auto-increment or sequence to determine any column values. 1500 * @param array $selectOptions Options for the SELECT part of the query, see 1501 * IDatabase::select() for details. 1502 * @param array $selectJoinConds Join conditions for the SELECT part of the query, see 1503 * IDatabase::select() for details. 1504 * @return bool Return true if no exception was thrown (deprecated since 1.33) 1505 * @throws DBError If an error occurs, {@see query} 1506 */ 1507 public function insertSelect( 1508 $destTable, 1509 $srcTable, 1510 $varMap, 1511 $conds, 1512 $fname = __METHOD__, 1513 $insertOptions = [], 1514 $selectOptions = [], 1515 $selectJoinConds = [] 1516 ); 1517 1518 /** 1519 * Determine if the RDBMS supports ORDER BY and LIMIT for separate subqueries within UNION 1520 * 1521 * @return bool 1522 */ 1523 public function unionSupportsOrderAndLimit(); 1524 1525 /** 1526 * Construct a UNION query 1527 * 1528 * This is used for providing overload point for other DB abstractions 1529 * not compatible with the MySQL syntax. 1530 * @param array $sqls SQL statements to combine 1531 * @param bool $all Either IDatabase::UNION_ALL or IDatabase::UNION_DISTINCT 1532 * @return string SQL fragment 1533 */ 1534 public function unionQueries( $sqls, $all ); 1535 1536 /** 1537 * Construct a UNION query for permutations of conditions 1538 * 1539 * Databases sometimes have trouble with queries that have multiple values 1540 * for multiple condition parameters combined with limits and ordering. 1541 * This method constructs queries for the Cartesian product of the 1542 * conditions and unions them all together. 1543 * 1544 * @see IDatabase::select() 1545 * @param string|array $table Table name 1546 * @param string|array $vars Field names 1547 * @param array $permute_conds Conditions for the Cartesian product. Keys 1548 * are field names, values are arrays of the possible values for that 1549 * field. 1550 * @param string|array $extra_conds Additional conditions to include in the 1551 * query. 1552 * @param string $fname Caller function name 1553 * @param string|array $options Query options. In addition to the options 1554 * recognized by IDatabase::select(), the following may be used: 1555 * - NOTALL: Set to use UNION instead of UNION ALL. 1556 * - INNER ORDER BY: If specified and supported, subqueries will use this 1557 * instead of ORDER BY. 1558 * @param string|array $join_conds Join conditions 1559 * @return string SQL query string. 1560 * @since 1.30 1561 */ 1562 public function unionConditionPermutations( 1563 $table, 1564 $vars, 1565 array $permute_conds, 1566 $extra_conds = '', 1567 $fname = __METHOD__, 1568 $options = [], 1569 $join_conds = [] 1570 ); 1571 1572 /** 1573 * Returns an SQL expression for a simple conditional 1574 * 1575 * This doesn't need to be overridden unless CASE isn't supported in the RDBMS. 1576 * 1577 * @param string|array $cond SQL condition expression (yields a boolean) 1578 * @param string $caseTrueExpression SQL expression to return when the condition is true 1579 * @param string $caseFalseExpression SQL expression to return when the condition is false 1580 * @return string SQL fragment 1581 */ 1582 public function conditional( $cond, $caseTrueExpression, $caseFalseExpression ); 1583 1584 /** 1585 * Returns a SQL expression for simple string replacement (e.g. REPLACE() in mysql) 1586 * 1587 * @param string $orig Column to modify 1588 * @param string $old Column to seek 1589 * @param string $new Column to replace with 1590 * @return string 1591 */ 1592 public function strreplace( $orig, $old, $new ); 1593 1594 /** 1595 * Determines how long the server has been up 1596 * 1597 * @return int 1598 * @throws DBError 1599 */ 1600 public function getServerUptime(); 1601 1602 /** 1603 * Determines if the last failure was due to a deadlock 1604 * 1605 * Note that during a deadlock, the prior transaction will have been lost 1606 * 1607 * @return bool 1608 */ 1609 public function wasDeadlock(); 1610 1611 /** 1612 * Determines if the last failure was due to a lock timeout 1613 * 1614 * Note that during a lock wait timeout, the prior transaction will have been lost 1615 * 1616 * @return bool 1617 */ 1618 public function wasLockTimeout(); 1619 1620 /** 1621 * Determines if the last query error was due to a dropped connection 1622 * 1623 * Note that during a connection loss, the prior transaction will have been lost 1624 * 1625 * @return bool 1626 * @since 1.31 1627 */ 1628 public function wasConnectionLoss(); 1629 1630 /** 1631 * Determines if the last failure was due to the database being read-only 1632 * 1633 * @return bool 1634 */ 1635 public function wasReadOnlyError(); 1636 1637 /** 1638 * Determines if the last query error was due to something outside of the query itself 1639 * 1640 * Note that the transaction may have been lost, discarding prior writes and results 1641 * 1642 * @return bool 1643 */ 1644 public function wasErrorReissuable(); 1645 1646 /** 1647 * Wait for the replica DB to catch up to a given primary DB position 1648 * 1649 * Note that this does not start any new transactions. If any existing transaction 1650 * is flushed, and this is called, then queries will reflect the point the DB was synced 1651 * up to (on success) without interference from REPEATABLE-READ snapshots. 1652 * 1653 * @param DBPrimaryPos $pos 1654 * @param int $timeout The maximum number of seconds to wait for synchronisation 1655 * @return int|null Zero if the replica DB was past that position already, 1656 * greater than zero if we waited for some period of time, less than 1657 * zero if it timed out, and null on error 1658 * @throws DBError If an error occurs, {@see query} 1659 * @since 1.37 1660 */ 1661 public function primaryPosWait( DBPrimaryPos $pos, $timeout ); 1662 1663 /** 1664 * @deprecated since 1.37; use primaryPosWait() instead. 1665 * @param DBPrimaryPos $pos 1666 * @param int $timeout The maximum number of seconds to wait for synchronisation 1667 * @return int|null Zero if the replica DB was past that position already, 1668 * greater than zero if we waited for some period of time, less than 1669 * zero if it timed out, and null on error 1670 * @throws DBError If an error occurs, {@see query} 1671 */ 1672 public function masterPosWait( DBPrimaryPos $pos, $timeout ); 1673 1674 /** 1675 * Get the replication position of this replica DB 1676 * 1677 * @return DBPrimaryPos|bool False if this is not a replica DB 1678 * @throws DBError If an error occurs, {@see query} 1679 */ 1680 public function getReplicaPos(); 1681 1682 /** 1683 * Get the position of this primary DB 1684 * 1685 * @return DBPrimaryPos|bool False if this is not a primary DB 1686 * @throws DBError If an error occurs, {@see query} 1687 * @since 1.37 1688 */ 1689 public function getPrimaryPos(); 1690 1691 /** 1692 * @deprecated since 1.37; use getPrimaryPos() instead. 1693 * @return DBPrimaryPos|bool False if this is not a primary DB 1694 * @throws DBError If an error occurs, {@see query} 1695 */ 1696 public function getMasterPos(); 1697 1698 /** 1699 * @return bool Whether the DB is marked as read-only server-side 1700 * @throws DBError If an error occurs, {@see query} 1701 * @since 1.28 1702 */ 1703 public function serverIsReadOnly(); 1704 1705 /** 1706 * Run a callback when the current transaction commits or rolls back 1707 * 1708 * An error is thrown if no transaction is pending. 1709 * 1710 * When transaction round mode (DBO_TRX) is set, the callback will run at the end 1711 * of the round, just after all peer transactions COMMIT/ROLLBACK. 1712 * 1713 * This IDatabase instance will start off in auto-commit mode when the callback starts. 1714 * The use of other IDatabase handles from the callback should be avoided unless they are 1715 * known to be in auto-commit mode. Callbacks that create transactions via begin() or 1716 * startAtomic() must have matching calls to commit()/endAtomic(). 1717 * 1718 * Use this method only for the following purposes: 1719 * - (a) Release of cooperative locks on resources 1720 * - (b) Cancellation of in-proccess deferred tasks 1721 * 1722 * The callback takes the following arguments: 1723 * - How the current atomic section (if any) or overall transaction (otherwise) ended 1724 * (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK) 1725 * - This IDatabase instance (since 1.32) 1726 * 1727 * Callbacks will execute in the order they were enqueued. 1728 * 1729 * @note Use onAtomicSectionCancel() to take action as soon as an atomic section is cancelled 1730 * 1731 * @param callable $callback 1732 * @param string $fname Caller name 1733 * @throws DBError If an error occurs, {@see query} 1734 * @throws Exception If the callback runs immediately and an error occurs in it 1735 * @since 1.28 1736 */ 1737 public function onTransactionResolution( callable $callback, $fname = __METHOD__ ); 1738 1739 /** 1740 * Run a callback when the current transaction commits or now if there is none 1741 * 1742 * If there is a transaction and it is rolled back, then the callback is cancelled. 1743 * 1744 * When transaction round mode (DBO_TRX) is set, the callback will run at the end 1745 * of the round, just after all peer transactions COMMIT. If the transaction round 1746 * is rolled back, then the callback is cancelled. 1747 * 1748 * This IDatabase instance will start off in auto-commit mode when the callback starts. 1749 * The use of other IDatabase handles from the callback should be avoided unless they are 1750 * known to be in auto-commit mode. Callbacks that create transactions via begin() or 1751 * startAtomic() must have matching calls to commit()/endAtomic(). 1752 * 1753 * Use this method only for the following purposes: 1754 * - (a) RDBMS updates, prone to lock timeouts/deadlocks, that do not require 1755 * atomicity with respect to the updates in the current transaction (if any) 1756 * - (b) Purges to lightweight cache services due to RDBMS updates 1757 * - (c) Updates to secondary DBs/stores that must only commit once the updates in 1758 * the current transaction (if any) are committed (e.g. insert user account row 1759 * to DB1, then, initialize corresponding LDAP account) 1760 * 1761 * The callback takes the following arguments: 1762 * - How the transaction ended (IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_IDLE) 1763 * - This IDatabase instance (since 1.32) 1764 * 1765 * Callbacks will execute in the order they were enqueued. 1766 * 1767 * @param callable $callback 1768 * @param string $fname Caller name 1769 * @throws DBError If an error occurs, {@see query} 1770 * @throws Exception If the callback runs immediately and an error occurs in it 1771 * @since 1.32 1772 */ 1773 public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ); 1774 1775 /** 1776 * Alias for onTransactionCommitOrIdle() for backwards-compatibility 1777 * 1778 * @param callable $callback 1779 * @param string $fname 1780 * @since 1.20 1781 * @deprecated Since 1.32 1782 */ 1783 public function onTransactionIdle( callable $callback, $fname = __METHOD__ ); 1784 1785 /** 1786 * Run a callback before the current transaction commits or now if there is none 1787 * 1788 * If there is a transaction and it is rolled back, then the callback is cancelled. 1789 * 1790 * When transaction round mode (DBO_TRX) is set, the callback will run at the end 1791 * of the round, just after all peer transactions COMMIT. If the transaction round 1792 * is rolled back, then the callback is cancelled. 1793 * 1794 * If there is no current transaction, one will be created to wrap the callback. 1795 * Callbacks cannot use begin()/commit() to manage transactions. The use of other 1796 * IDatabase handles from the callback should be avoided. 1797 * 1798 * Use this method only for the following purposes: 1799 * - a) RDBMS updates, prone to lock timeouts/deadlocks, that require atomicity 1800 * with respect to the updates in the current transaction (if any) 1801 * - b) Purges to lightweight cache services due to RDBMS updates 1802 * 1803 * The callback takes the one argument: 1804 * - This IDatabase instance (since 1.32) 1805 * 1806 * Callbacks will execute in the order they were enqueued. 1807 * 1808 * @param callable $callback 1809 * @param string $fname Caller name 1810 * @throws DBError If an error occurs, {@see query} 1811 * @throws Exception If the callback runs immediately and an error occurs in it 1812 * @since 1.22 1813 */ 1814 public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ); 1815 1816 /** 1817 * Run a callback when the atomic section is cancelled 1818 * 1819 * The callback is run just after the current atomic section, any outer 1820 * atomic section, or the whole transaction is rolled back. 1821 * 1822 * An error is thrown if no atomic section is pending. The atomic section 1823 * need not have been created with the ATOMIC_CANCELABLE flag. 1824 * 1825 * Queries in the function may be running in the context of an outer 1826 * transaction or may be running in AUTOCOMMIT mode. The callback should 1827 * use atomic sections if necessary. 1828 * 1829 * @note do not assume that *other* IDatabase instances will be AUTOCOMMIT mode 1830 * 1831 * The callback takes the following arguments: 1832 * - IDatabase::TRIGGER_CANCEL or IDatabase::TRIGGER_ROLLBACK 1833 * - This IDatabase instance 1834 * 1835 * @param callable $callback 1836 * @param string $fname Caller name 1837 * @since 1.34 1838 */ 1839 public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ); 1840 1841 /** 1842 * Run a callback after each time any transaction commits or rolls back 1843 * 1844 * The callback takes two arguments: 1845 * - IDatabase::TRIGGER_COMMIT or IDatabase::TRIGGER_ROLLBACK 1846 * - This IDatabase object 1847 * Callbacks must commit any transactions that they begin. 1848 * 1849 * Registering a callback here will not affect writesOrCallbacks() pending. 1850 * 1851 * Since callbacks from this or onTransactionCommitOrIdle() can start and end transactions, 1852 * a single call to IDatabase::commit might trigger multiple runs of the listener callbacks. 1853 * 1854 * @param string $name Callback name 1855 * @param callable|null $callback Use null to unset a listener 1856 * @since 1.28 1857 */ 1858 public function setTransactionListener( $name, callable $callback = null ); 1859 1860 /** 1861 * Begin an atomic section of SQL statements 1862 * 1863 * Start an implicit transaction if no transaction is already active, set a savepoint 1864 * (if $cancelable is ATOMIC_CANCELABLE), and track the given section name to enforce 1865 * that the transaction is not committed prematurely. The end of the section must be 1866 * signified exactly once, either by endAtomic() or cancelAtomic(). Sections can have 1867 * have layers of inner sections (sub-sections), but all sections must be ended in order 1868 * of innermost to outermost. Transactions cannot be started or committed until all 1869 * atomic sections are closed. 1870 * 1871 * ATOMIC_CANCELABLE is useful when the caller needs to handle specific failure cases 1872 * by discarding the section's writes. This should not be used for failures when: 1873 * - upsert() could easily be used instead 1874 * - insert() with IGNORE could easily be used instead 1875 * - select() with FOR UPDATE could be checked before issuing writes instead 1876 * - The failure is from code that runs after the first write but doesn't need to 1877 * - The failures are from contention solvable via onTransactionPreCommitOrIdle() 1878 * - The failures are deadlocks; the RDBMs usually discard the whole transaction 1879 * 1880 * @note callers must use additional measures for situations involving two or more 1881 * (peer) transactions (e.g. updating two database servers at once). The transaction 1882 * and savepoint logic of this method only applies to this specific IDatabase instance. 1883 * 1884 * Example usage: 1885 * @code 1886 * // Start a transaction if there isn't one already 1887 * $dbw->startAtomic( __METHOD__ ); 1888 * // Serialize these thread table updates 1889 * $dbw->select( 'thread', '1', [ 'td_id' => $tid ], __METHOD__, 'FOR UPDATE' ); 1890 * // Add a new comment for the thread 1891 * $dbw->insert( 'comment', $row, __METHOD__ ); 1892 * $cid = $db->insertId(); 1893 * // Update thread reference to last comment 1894 * $dbw->update( 'thread', [ 'td_latest' => $cid ], [ 'td_id' => $tid ], __METHOD__ ); 1895 * // Demark the end of this conceptual unit of updates 1896 * $dbw->endAtomic( __METHOD__ ); 1897 * @endcode 1898 * 1899 * Example usage (atomic changes that might have to be discarded): 1900 * @code 1901 * // Start a transaction if there isn't one already 1902 * $sectionId = $dbw->startAtomic( __METHOD__, $dbw::ATOMIC_CANCELABLE ); 1903 * // Create new record metadata row 1904 * $dbw->insert( 'records', $row, __METHOD__ ); 1905 * // Figure out where to store the data based on the new row's ID 1906 * $path = $recordDirectory . '/' . $dbw->insertId(); 1907 * // Write the record data to the storage system 1908 * $status = $fileBackend->create( [ 'dst' => $path, 'content' => $data ] ); 1909 * if ( $status->isOK() ) { 1910 * // Try to cleanup files orphaned by transaction rollback 1911 * $dbw->onTransactionResolution( 1912 * function ( $type ) use ( $fileBackend, $path ) { 1913 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) { 1914 * $fileBackend->delete( [ 'src' => $path ] ); 1915 * } 1916 * }, 1917 * __METHOD__ 1918 * ); 1919 * // Demark the end of this conceptual unit of updates 1920 * $dbw->endAtomic( __METHOD__ ); 1921 * } else { 1922 * // Discard these writes from the transaction (preserving prior writes) 1923 * $dbw->cancelAtomic( __METHOD__, $sectionId ); 1924 * } 1925 * @endcode 1926 * 1927 * @since 1.23 1928 * @param string $fname 1929 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a 1930 * savepoint and enable self::cancelAtomic() for this section. 1931 * @return AtomicSectionIdentifier section ID token 1932 * @throws DBError If an error occurs, {@see query} 1933 */ 1934 public function startAtomic( $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE ); 1935 1936 /** 1937 * Ends an atomic section of SQL statements 1938 * 1939 * Ends the next section of atomic SQL statements and commits the transaction 1940 * if necessary. 1941 * 1942 * @since 1.23 1943 * @see IDatabase::startAtomic 1944 * @param string $fname 1945 * @throws DBError If an error occurs, {@see query} 1946 */ 1947 public function endAtomic( $fname = __METHOD__ ); 1948 1949 /** 1950 * Cancel an atomic section of SQL statements 1951 * 1952 * This will roll back only the statements executed since the start of the 1953 * most recent atomic section, and close that section. If a transaction was 1954 * open before the corresponding startAtomic() call, any statements before 1955 * that call are *not* rolled back and the transaction remains open. If the 1956 * corresponding startAtomic() implicitly started a transaction, that 1957 * transaction is rolled back. 1958 * 1959 * @note callers must use additional measures for situations involving two or more 1960 * (peer) transactions (e.g. updating two database servers at once). The transaction 1961 * and savepoint logic of startAtomic() are bound to specific IDatabase instances. 1962 * 1963 * Note that a call to IDatabase::rollback() will also roll back any open atomic sections. 1964 * 1965 * @note As a micro-optimization to save a few DB calls, this method may only 1966 * be called when startAtomic() was called with the ATOMIC_CANCELABLE flag. 1967 * @since 1.31 1968 * @see IDatabase::startAtomic 1969 * @param string $fname 1970 * @param AtomicSectionIdentifier|null $sectionId Section ID from startAtomic(); 1971 * passing this enables cancellation of unclosed nested sections [optional] 1972 * @throws DBError If an error occurs, {@see query} 1973 */ 1974 public function cancelAtomic( $fname = __METHOD__, AtomicSectionIdentifier $sectionId = null ); 1975 1976 /** 1977 * Perform an atomic section of reversable SQL statements from a callback 1978 * 1979 * The $callback takes the following arguments: 1980 * - This database object 1981 * - The value of $fname 1982 * 1983 * This will execute the callback inside a pair of startAtomic()/endAtomic() calls. 1984 * If any exception occurs during execution of the callback, it will be handled as follows: 1985 * - If $cancelable is ATOMIC_CANCELABLE, cancelAtomic() will be called to back out any 1986 * (and only) statements executed during the atomic section. If that succeeds, then the 1987 * exception will be re-thrown; if it fails, then a different exception will be thrown 1988 * and any further query attempts will fail until rollback() is called. 1989 * - If $cancelable is ATOMIC_NOT_CANCELABLE, cancelAtomic() will be called to mark the 1990 * end of the section and the error will be re-thrown. Any further query attempts will 1991 * fail until rollback() is called. 1992 * 1993 * This method is convenient for letting calls to the caller of this method be wrapped 1994 * in a try/catch blocks for exception types that imply that the caller failed but was 1995 * able to properly discard the changes it made in the transaction. This method can be 1996 * an alternative to explicit calls to startAtomic()/endAtomic()/cancelAtomic(). 1997 * 1998 * Example usage, "RecordStore::save" method: 1999 * @code 2000 * $dbw->doAtomicSection( __METHOD__, function ( $dbw ) use ( $record ) { 2001 * // Create new record metadata row 2002 * $dbw->insert( 'records', $record->toArray(), __METHOD__ ); 2003 * // Figure out where to store the data based on the new row's ID 2004 * $path = $this->recordDirectory . '/' . $dbw->insertId(); 2005 * // Write the record data to the storage system; 2006 * // blob store throughs StoreFailureException on failure 2007 * $this->blobStore->create( $path, $record->getJSON() ); 2008 * // Try to cleanup files orphaned by transaction rollback 2009 * $dbw->onTransactionResolution( 2010 * function ( $type ) use ( $path ) { 2011 * if ( $type === IDatabase::TRIGGER_ROLLBACK ) { 2012 * $this->blobStore->delete( $path ); 2013 * } 2014 * }, 2015 * __METHOD__ 2016 * ); 2017 * }, $dbw::ATOMIC_CANCELABLE ); 2018 * @endcode 2019 * 2020 * Example usage, caller of the "RecordStore::save" method: 2021 * @code 2022 * $dbw->startAtomic( __METHOD__ ); 2023 * // ...various SQL writes happen... 2024 * try { 2025 * $recordStore->save( $record ); 2026 * } catch ( StoreFailureException $e ) { 2027 * // ...various SQL writes happen... 2028 * } 2029 * // ...various SQL writes happen... 2030 * $dbw->endAtomic( __METHOD__ ); 2031 * @endcode 2032 * 2033 * @see Database::startAtomic 2034 * @see Database::endAtomic 2035 * @see Database::cancelAtomic 2036 * 2037 * @param string $fname Caller name (usually __METHOD__) 2038 * @param callable $callback Callback that issues DB updates 2039 * @param string $cancelable Pass self::ATOMIC_CANCELABLE to use a 2040 * savepoint and enable self::cancelAtomic() for this section. 2041 * @return mixed Result of the callback (since 1.28) 2042 * @throws DBError If an error occurs, {@see query} 2043 * @throws Exception If an error occurs in the callback 2044 * @since 1.27; prior to 1.31 this did a rollback() instead of 2045 * cancelAtomic(), and assumed no callers up the stack would ever try to 2046 * catch the exception. 2047 */ 2048 public function doAtomicSection( 2049 $fname, callable $callback, $cancelable = self::ATOMIC_NOT_CANCELABLE 2050 ); 2051 2052 /** 2053 * Begin a transaction 2054 * 2055 * Only call this from code with outer transaction scope. 2056 * See https://www.mediawiki.org/wiki/Database_transactions for details. 2057 * Nesting of transactions is not supported. 2058 * 2059 * Note that when the DBO_TRX flag is set (which is usually the case for web 2060 * requests, but not for maintenance scripts), any previous database query 2061 * will have started a transaction automatically. 2062 * 2063 * Nesting of transactions is not supported. Attempts to nest transactions 2064 * will cause a warning, unless the current transaction was started 2065 * automatically because of the DBO_TRX flag. 2066 * 2067 * @param string $fname Calling function name 2068 * @param string $mode A situationally valid IDatabase::TRANSACTION_* constant [optional] 2069 * @throws DBError If an error occurs, {@see query} 2070 */ 2071 public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ); 2072 2073 /** 2074 * Commits a transaction previously started using begin() 2075 * 2076 * If no transaction is in progress, a warning is issued. 2077 * 2078 * Only call this from code with outer transaction scope. 2079 * See https://www.mediawiki.org/wiki/Database_transactions for details. 2080 * Nesting of transactions is not supported. 2081 * 2082 * @param string $fname 2083 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_* 2084 * constant to disable warnings about explicitly committing implicit transactions, 2085 * or calling commit when no transaction is in progress. 2086 * This will trigger an exception if there is an ongoing explicit transaction. 2087 * Only set the flush flag if you are sure that these warnings are not applicable, 2088 * and no explicit transactions are open. 2089 * @throws DBError If an error occurs, {@see query} 2090 */ 2091 public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ); 2092 2093 /** 2094 * Rollback a transaction previously started using begin() 2095 * 2096 * Only call this from code with outer transaction scope. 2097 * See https://www.mediawiki.org/wiki/Database_transactions for details. 2098 * Nesting of transactions is not supported. If a serious unexpected error occurs, 2099 * throwing an Exception is preferable, using a pre-installed error handler to trigger 2100 * rollback (in any case, failure to issue COMMIT will cause rollback server-side). 2101 * 2102 * Query, connection, and onTransaction* callback errors will be suppressed and logged. 2103 * 2104 * @param string $fname Calling function name 2105 * @param string $flush Flush flag, set to a situationally valid IDatabase::FLUSHING_* 2106 * constant to disable warnings about calling rollback when no transaction is in 2107 * progress. This will silently break any ongoing explicit transaction. Only set the 2108 * flush flag if you are sure that it is safe to ignore these warnings in your context. 2109 * @throws DBError If an error occurs, {@see query} 2110 * @since 1.23 Added $flush parameter 2111 */ 2112 public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ); 2113 2114 /** 2115 * Commit any transaction but error out if writes or callbacks are pending 2116 * 2117 * This is intended for clearing out REPEATABLE-READ snapshots so that callers can 2118 * see a new point-in-time of the database. This is useful when one of many transaction 2119 * rounds finished and significant time will pass in the script's lifetime. It is also 2120 * useful to call on a replica DB after waiting on replication to catch up to the primary DB. 2121 * 2122 * @param string $fname Calling function name 2123 * @param string $flush Flush flag, set to situationally valid IDatabase::FLUSHING_* 2124 * constant to disable warnings about explicitly committing implicit transactions, 2125 * or calling commit when no transaction is in progress. 2126 * This will trigger an exception if there is an ongoing explicit transaction. 2127 * Only set the flush flag if you are sure that these warnings are not applicable, 2128 * and no explicit transactions are open. 2129 * @throws DBError If an error occurs, {@see query} 2130 * @since 1.28 2131 * @since 1.34 Added $flush parameter 2132 */ 2133 public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ); 2134 2135 /** 2136 * Convert a timestamp in one of the formats accepted by ConvertibleTimestamp 2137 * to the format used for inserting into timestamp fields in this DBMS 2138 * 2139 * The result is unquoted, and needs to be passed through addQuotes() 2140 * before it can be included in raw SQL. 2141 * 2142 * @param string|int $ts 2143 * 2144 * @return string 2145 */ 2146 public function timestamp( $ts = 0 ); 2147 2148 /** 2149 * Convert a timestamp in one of the formats accepted by ConvertibleTimestamp 2150 * to the format used for inserting into timestamp fields in this DBMS 2151 * 2152 * If NULL is input, it is passed through, allowing NULL values to be inserted 2153 * into timestamp fields. 2154 * 2155 * The result is unquoted, and needs to be passed through addQuotes() 2156 * before it can be included in raw SQL. 2157 * 2158 * @param string|int|null $ts 2159 * 2160 * @return string|null 2161 */ 2162 public function timestampOrNull( $ts = null ); 2163 2164 /** 2165 * Ping the server and try to reconnect if it there is no connection 2166 * 2167 * @param float|null &$rtt Value to store the estimated RTT [optional] 2168 * @return bool Success or failure 2169 */ 2170 public function ping( &$rtt = null ); 2171 2172 /** 2173 * Get the amount of replication lag for this database server 2174 * 2175 * Callers should avoid using this method while a transaction is active 2176 * 2177 * @return float|int|false Database replication lag in seconds or false on error 2178 * @throws DBError If an error occurs, {@see query} 2179 */ 2180 public function getLag(); 2181 2182 /** 2183 * Get the replica DB lag when the current transaction started 2184 * or a general lag estimate if not transaction is active 2185 * 2186 * This is useful when transactions might use snapshot isolation 2187 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data 2188 * is this lag plus transaction duration. If they don't, it is still 2189 * safe to be pessimistic. In AUTOCOMMIT mode, this still gives an 2190 * indication of the staleness of subsequent reads. 2191 * 2192 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN) 2193 * @throws DBError If an error occurs, {@see query} 2194 * @since 1.27 2195 */ 2196 public function getSessionLagStatus(); 2197 2198 /** 2199 * Return the maximum number of items allowed in a list, or 0 for unlimited 2200 * 2201 * @return int 2202 */ 2203 public function maxListLen(); 2204 2205 /** 2206 * Some DBMSs have a special format for inserting into blob fields, they 2207 * don't allow simple quoted strings to be inserted. To insert into such 2208 * a field, pass the data through this function before passing it to 2209 * IDatabase::insert(). 2210 * 2211 * @param string $b 2212 * @return string|Blob 2213 * @throws DBError 2214 */ 2215 public function encodeBlob( $b ); 2216 2217 /** 2218 * Some DBMSs return a special placeholder object representing blob fields 2219 * in result objects. Pass the object through this function to return the 2220 * original string. 2221 * 2222 * @param string|Blob $b 2223 * @return string 2224 * @throws DBError 2225 */ 2226 public function decodeBlob( $b ); 2227 2228 /** 2229 * Override database's default behavior. $options include: 2230 * 'connTimeout' : Set the connection timeout value in seconds. 2231 * May be useful for very long batch queries such as 2232 * full-wiki dumps, where a single query reads out over 2233 * hours or days. 2234 * 2235 * @param array $options 2236 * @return void 2237 * @throws DBError If an error occurs, {@see query} 2238 */ 2239 public function setSessionOptions( array $options ); 2240 2241 /** 2242 * Set schema variables to be used when streaming commands from SQL files or stdin 2243 * 2244 * Variables appear as SQL comments and are substituted by their corresponding values 2245 * 2246 * @param array|null $vars Map of (variable => value) or null to use the defaults 2247 */ 2248 public function setSchemaVars( $vars ); 2249 2250 /** 2251 * Check to see if a named lock is not locked by any thread (non-blocking) 2252 * 2253 * @param string $lockName Name of lock to poll 2254 * @param string $method Name of method calling us 2255 * @return bool 2256 * @throws DBError If an error occurs, {@see query} 2257 * @since 1.20 2258 */ 2259 public function lockIsFree( $lockName, $method ); 2260 2261 /** 2262 * Acquire a named lock 2263 * 2264 * Named locks are not related to transactions 2265 * 2266 * @param string $lockName Name of lock to aquire 2267 * @param string $method Name of the calling method 2268 * @param int $timeout Acquisition timeout in seconds (0 means non-blocking) 2269 * @param int $flags Bit field of IDatabase::LOCK_* constants 2270 * @return bool Success 2271 * @throws DBError If an error occurs, {@see query} 2272 */ 2273 public function lock( $lockName, $method, $timeout = 5, $flags = 0 ); 2274 2275 /** 2276 * Release a lock 2277 * 2278 * Named locks are not related to transactions 2279 * 2280 * @param string $lockName Name of lock to release 2281 * @param string $method Name of the calling method 2282 * @return bool Success 2283 * @throws DBError If an error occurs, {@see query} 2284 */ 2285 public function unlock( $lockName, $method ); 2286 2287 /** 2288 * Acquire a named lock, flush any transaction, and return an RAII style unlocker object 2289 * 2290 * Only call this from outer transaction scope and when only one DB will be affected. 2291 * See https://www.mediawiki.org/wiki/Database_transactions for details. 2292 * 2293 * This is suitable for transactions that need to be serialized using cooperative locks, 2294 * where each transaction can see each others' changes. Any transaction is flushed to clear 2295 * out stale REPEATABLE-READ snapshot data. Once the returned object falls out of PHP scope, 2296 * the lock will be released unless a transaction is active. If one is active, then the lock 2297 * will be released when it either commits or rolls back. 2298 * 2299 * If the lock acquisition failed, then no transaction flush happens, and null is returned. 2300 * 2301 * @param string $lockKey Name of lock to release 2302 * @param string $fname Name of the calling method 2303 * @param int $timeout Acquisition timeout in seconds 2304 * @return ScopedCallback|null 2305 * @throws DBError If an error occurs, {@see query} 2306 * @since 1.27 2307 */ 2308 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ); 2309 2310 /** 2311 * Check to see if a named lock used by lock() use blocking queues 2312 * 2313 * @return bool 2314 * @since 1.26 2315 */ 2316 public function namedLocksEnqueue(); 2317 2318 /** 2319 * Find out when 'infinity' is. Most DBMSes support this. This is a special 2320 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well 2321 * because "i" sorts after all numbers. 2322 * 2323 * @return string 2324 */ 2325 public function getInfinity(); 2326 2327 /** 2328 * Encode an expiry time into the DBMS dependent format 2329 * 2330 * @param string $expiry Timestamp for expiry, or the 'infinity' string 2331 * @return string 2332 */ 2333 public function encodeExpiry( $expiry ); 2334 2335 /** 2336 * Decode an expiry time into a DBMS independent format 2337 * 2338 * @param string $expiry DB timestamp field value for expiry 2339 * @param int $format TS_* constant, defaults to TS_MW 2340 * @return string 2341 */ 2342 public function decodeExpiry( $expiry, $format = TS_MW ); 2343 2344 /** 2345 * Allow or deny "big selects" for this session only. This is done by setting 2346 * the sql_big_selects session variable. 2347 * 2348 * This is a MySQL-specific feature. 2349 * 2350 * @param bool|string $value True for allow, false for deny, or "default" to 2351 * restore the initial value 2352 */ 2353 public function setBigSelects( $value = true ); 2354 2355 /** 2356 * @return bool Whether this DB is read-only 2357 * @since 1.27 2358 */ 2359 public function isReadOnly(); 2360 2361 /** 2362 * Make certain table names use their own database, schema, and table prefix 2363 * when passed into SQL queries pre-escaped and without a qualified database name 2364 * 2365 * For example, "user" can be converted to "myschema.mydbname.user" for convenience. 2366 * Appearances like `user`, somedb.user, somedb.someschema.user will used literally. 2367 * 2368 * Calling this twice will completely clear any old table aliases. Also, note that 2369 * callers are responsible for making sure the schemas and databases actually exist. 2370 * 2371 * @param array[] $aliases Map of (table => (dbname, schema, prefix) map) 2372 * @since 1.28 2373 */ 2374 public function setTableAliases( array $aliases ); 2375 2376 /** 2377 * Convert certain index names to alternative names before querying the DB 2378 * 2379 * Note that this applies to indexes regardless of the table they belong to. 2380 * 2381 * This can be employed when an index was renamed X => Y in code, but the new Y-named 2382 * indexes were not yet built on all DBs. After all the Y-named ones are added by the DBA, 2383 * the aliases can be removed, and then the old X-named indexes dropped. 2384 * 2385 * @param string[] $aliases 2386 * @since 1.31 2387 */ 2388 public function setIndexAliases( array $aliases ); 2389 2390 /** 2391 * Get a debugging string that mentions the database type, the ID of this instance, 2392 * and the ID of any underlying connection resource or driver object if one is present 2393 * 2394 * @return string "<db type> object #<X>" or "<db type> object #<X> (resource/handle id #<Y>)" 2395 * @since 1.34 2396 */ 2397 public function __toString(); 2398} 2399 2400/** 2401 * @deprecated since 1.29 2402 */ 2403class_alias( IDatabase::class, 'IDatabase' ); 2404