PageRenderTime 65ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/db/Database.php

https://github.com/spenser-roark/OOUG-Wiki
PHP | 3453 lines | 1361 code | 363 blank | 1729 comment | 286 complexity | 25cef59bff6341beb07882104ab8d1ed MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * @defgroup Database Database
  4. *
  5. * @file
  6. * @ingroup Database
  7. * This file deals with database interface functions
  8. * and query specifics/optimisations
  9. */
  10. /** Number of times to re-try an operation in case of deadlock */
  11. define( 'DEADLOCK_TRIES', 4 );
  12. /** Minimum time to wait before retry, in microseconds */
  13. define( 'DEADLOCK_DELAY_MIN', 500000 );
  14. /** Maximum time to wait before retry */
  15. define( 'DEADLOCK_DELAY_MAX', 1500000 );
  16. /**
  17. * Base interface for all DBMS-specific code. At a bare minimum, all of the
  18. * following must be implemented to support MediaWiki
  19. *
  20. * @file
  21. * @ingroup Database
  22. */
  23. interface DatabaseType {
  24. /**
  25. * Get the type of the DBMS, as it appears in $wgDBtype.
  26. *
  27. * @return string
  28. */
  29. function getType();
  30. /**
  31. * Open a connection to the database. Usually aborts on failure
  32. *
  33. * @param $server String: database server host
  34. * @param $user String: database user name
  35. * @param $password String: database user password
  36. * @param $dbName String: database name
  37. * @return bool
  38. * @throws DBConnectionError
  39. */
  40. function open( $server, $user, $password, $dbName );
  41. /**
  42. * Fetch the next row from the given result object, in object form.
  43. * Fields can be retrieved with $row->fieldname, with fields acting like
  44. * member variables.
  45. *
  46. * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
  47. * @return Row object
  48. * @throws DBUnexpectedError Thrown if the database returns an error
  49. */
  50. function fetchObject( $res );
  51. /**
  52. * Fetch the next row from the given result object, in associative array
  53. * form. Fields are retrieved with $row['fieldname'].
  54. *
  55. * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
  56. * @return Row object
  57. * @throws DBUnexpectedError Thrown if the database returns an error
  58. */
  59. function fetchRow( $res );
  60. /**
  61. * Get the number of rows in a result object
  62. *
  63. * @param $res Mixed: A SQL result
  64. * @return int
  65. */
  66. function numRows( $res );
  67. /**
  68. * Get the number of fields in a result object
  69. * @see http://www.php.net/mysql_num_fields
  70. *
  71. * @param $res Mixed: A SQL result
  72. * @return int
  73. */
  74. function numFields( $res );
  75. /**
  76. * Get a field name in a result object
  77. * @see http://www.php.net/mysql_field_name
  78. *
  79. * @param $res Mixed: A SQL result
  80. * @param $n Integer
  81. * @return string
  82. */
  83. function fieldName( $res, $n );
  84. /**
  85. * Get the inserted value of an auto-increment row
  86. *
  87. * The value inserted should be fetched from nextSequenceValue()
  88. *
  89. * Example:
  90. * $id = $dbw->nextSequenceValue('page_page_id_seq');
  91. * $dbw->insert('page',array('page_id' => $id));
  92. * $id = $dbw->insertId();
  93. *
  94. * @return int
  95. */
  96. function insertId();
  97. /**
  98. * Change the position of the cursor in a result object
  99. * @see http://www.php.net/mysql_data_seek
  100. *
  101. * @param $res Mixed: A SQL result
  102. * @param $row Mixed: Either MySQL row or ResultWrapper
  103. */
  104. function dataSeek( $res, $row );
  105. /**
  106. * Get the last error number
  107. * @see http://www.php.net/mysql_errno
  108. *
  109. * @return int
  110. */
  111. function lastErrno();
  112. /**
  113. * Get a description of the last error
  114. * @see http://www.php.net/mysql_error
  115. *
  116. * @return string
  117. */
  118. function lastError();
  119. /**
  120. * mysql_fetch_field() wrapper
  121. * Returns false if the field doesn't exist
  122. *
  123. * @param $table string: table name
  124. * @param $field string: field name
  125. *
  126. * @return Field
  127. */
  128. function fieldInfo( $table, $field );
  129. /**
  130. * Get information about an index into an object
  131. * @param $table string: Table name
  132. * @param $index string: Index name
  133. * @param $fname string: Calling function name
  134. * @return Mixed: Database-specific index description class or false if the index does not exist
  135. */
  136. function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
  137. /**
  138. * Get the number of rows affected by the last write query
  139. * @see http://www.php.net/mysql_affected_rows
  140. *
  141. * @return int
  142. */
  143. function affectedRows();
  144. /**
  145. * Wrapper for addslashes()
  146. *
  147. * @param $s string: to be slashed.
  148. * @return string: slashed string.
  149. */
  150. function strencode( $s );
  151. /**
  152. * Returns a wikitext link to the DB's website, e.g.,
  153. * return "[http://www.mysql.com/ MySQL]";
  154. * Should at least contain plain text, if for some reason
  155. * your database has no website.
  156. *
  157. * @return string: wikitext of a link to the server software's web site
  158. */
  159. static function getSoftwareLink();
  160. /**
  161. * A string describing the current software version, like from
  162. * mysql_get_server_info().
  163. *
  164. * @return string: Version information from the database server.
  165. */
  166. function getServerVersion();
  167. /**
  168. * A string describing the current software version, and possibly
  169. * other details in a user-friendly way. Will be listed on Special:Version, etc.
  170. * Use getServerVersion() to get machine-friendly information.
  171. *
  172. * @return string: Version information from the database server
  173. */
  174. function getServerInfo();
  175. }
  176. /**
  177. * Database abstraction object
  178. * @ingroup Database
  179. */
  180. abstract class DatabaseBase implements DatabaseType {
  181. # ------------------------------------------------------------------------------
  182. # Variables
  183. # ------------------------------------------------------------------------------
  184. protected $mLastQuery = '';
  185. protected $mDoneWrites = false;
  186. protected $mPHPError = false;
  187. protected $mServer, $mUser, $mPassword, $mDBname;
  188. /**
  189. * @var DatabaseBase
  190. */
  191. protected $mConn = null;
  192. protected $mOpened = false;
  193. protected $mTablePrefix;
  194. protected $mFlags;
  195. protected $mTrxLevel = 0;
  196. protected $mErrorCount = 0;
  197. protected $mLBInfo = array();
  198. protected $mFakeSlaveLag = null, $mFakeMaster = false;
  199. protected $mDefaultBigSelects = null;
  200. protected $mSchemaVars = false;
  201. protected $preparedArgs;
  202. protected $htmlErrors;
  203. protected $delimiter = ';';
  204. # ------------------------------------------------------------------------------
  205. # Accessors
  206. # ------------------------------------------------------------------------------
  207. # These optionally set a variable and return the previous state
  208. /**
  209. * A string describing the current software version, and possibly
  210. * other details in a user-friendly way. Will be listed on Special:Version, etc.
  211. * Use getServerVersion() to get machine-friendly information.
  212. *
  213. * @return string: Version information from the database server
  214. */
  215. public function getServerInfo() {
  216. return $this->getServerVersion();
  217. }
  218. /**
  219. * Boolean, controls output of large amounts of debug information.
  220. * @param $debug bool|null
  221. * - true to enable debugging
  222. * - false to disable debugging
  223. * - omitted or null to do nothing
  224. *
  225. * @return The previous value of the flag
  226. */
  227. function debug( $debug = null ) {
  228. return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
  229. }
  230. /**
  231. * Turns buffering of SQL result sets on (true) or off (false). Default is
  232. * "on".
  233. *
  234. * Unbuffered queries are very troublesome in MySQL:
  235. *
  236. * - If another query is executed while the first query is being read
  237. * out, the first query is killed. This means you can't call normal
  238. * MediaWiki functions while you are reading an unbuffered query result
  239. * from a normal wfGetDB() connection.
  240. *
  241. * - Unbuffered queries cause the MySQL server to use large amounts of
  242. * memory and to hold broad locks which block other queries.
  243. *
  244. * If you want to limit client-side memory, it's almost always better to
  245. * split up queries into batches using a LIMIT clause than to switch off
  246. * buffering.
  247. *
  248. * @param $buffer null|bool
  249. *
  250. * @return The previous value of the flag
  251. */
  252. function bufferResults( $buffer = null ) {
  253. if ( is_null( $buffer ) ) {
  254. return !(bool)( $this->mFlags & DBO_NOBUFFER );
  255. } else {
  256. return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
  257. }
  258. }
  259. /**
  260. * Turns on (false) or off (true) the automatic generation and sending
  261. * of a "we're sorry, but there has been a database error" page on
  262. * database errors. Default is on (false). When turned off, the
  263. * code should use lastErrno() and lastError() to handle the
  264. * situation as appropriate.
  265. *
  266. * @param $ignoreErrors bool|null
  267. *
  268. * @return bool The previous value of the flag.
  269. */
  270. function ignoreErrors( $ignoreErrors = null ) {
  271. return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
  272. }
  273. /**
  274. * Gets or sets the current transaction level.
  275. *
  276. * Historically, transactions were allowed to be "nested". This is no
  277. * longer supported, so this function really only returns a boolean.
  278. *
  279. * @param $level An integer (0 or 1), or omitted to leave it unchanged.
  280. * @return The previous value
  281. */
  282. function trxLevel( $level = null ) {
  283. return wfSetVar( $this->mTrxLevel, $level );
  284. }
  285. /**
  286. * Get/set the number of errors logged. Only useful when errors are ignored
  287. * @param $count The count to set, or omitted to leave it unchanged.
  288. * @return The error count
  289. */
  290. function errorCount( $count = null ) {
  291. return wfSetVar( $this->mErrorCount, $count );
  292. }
  293. /**
  294. * Get/set the table prefix.
  295. * @param $prefix The table prefix to set, or omitted to leave it unchanged.
  296. * @return The previous table prefix.
  297. */
  298. function tablePrefix( $prefix = null ) {
  299. return wfSetVar( $this->mTablePrefix, $prefix );
  300. }
  301. /**
  302. * Get properties passed down from the server info array of the load
  303. * balancer.
  304. *
  305. * @param $name string The entry of the info array to get, or null to get the
  306. * whole array
  307. *
  308. * @return LoadBalancer|null
  309. */
  310. function getLBInfo( $name = null ) {
  311. if ( is_null( $name ) ) {
  312. return $this->mLBInfo;
  313. } else {
  314. if ( array_key_exists( $name, $this->mLBInfo ) ) {
  315. return $this->mLBInfo[$name];
  316. } else {
  317. return null;
  318. }
  319. }
  320. }
  321. /**
  322. * Set the LB info array, or a member of it. If called with one parameter,
  323. * the LB info array is set to that parameter. If it is called with two
  324. * parameters, the member with the given name is set to the given value.
  325. *
  326. * @param $name
  327. * @param $value
  328. */
  329. function setLBInfo( $name, $value = null ) {
  330. if ( is_null( $value ) ) {
  331. $this->mLBInfo = $name;
  332. } else {
  333. $this->mLBInfo[$name] = $value;
  334. }
  335. }
  336. /**
  337. * Set lag time in seconds for a fake slave
  338. *
  339. * @param $lag int
  340. */
  341. function setFakeSlaveLag( $lag ) {
  342. $this->mFakeSlaveLag = $lag;
  343. }
  344. /**
  345. * Make this connection a fake master
  346. *
  347. * @param $enabled bool
  348. */
  349. function setFakeMaster( $enabled = true ) {
  350. $this->mFakeMaster = $enabled;
  351. }
  352. /**
  353. * Returns true if this database supports (and uses) cascading deletes
  354. *
  355. * @return bool
  356. */
  357. function cascadingDeletes() {
  358. return false;
  359. }
  360. /**
  361. * Returns true if this database supports (and uses) triggers (e.g. on the page table)
  362. *
  363. * @return bool
  364. */
  365. function cleanupTriggers() {
  366. return false;
  367. }
  368. /**
  369. * Returns true if this database is strict about what can be put into an IP field.
  370. * Specifically, it uses a NULL value instead of an empty string.
  371. *
  372. * @return bool
  373. */
  374. function strictIPs() {
  375. return false;
  376. }
  377. /**
  378. * Returns true if this database uses timestamps rather than integers
  379. *
  380. * @return bool
  381. */
  382. function realTimestamps() {
  383. return false;
  384. }
  385. /**
  386. * Returns true if this database does an implicit sort when doing GROUP BY
  387. *
  388. * @return bool
  389. */
  390. function implicitGroupby() {
  391. return true;
  392. }
  393. /**
  394. * Returns true if this database does an implicit order by when the column has an index
  395. * For example: SELECT page_title FROM page LIMIT 1
  396. *
  397. * @return bool
  398. */
  399. function implicitOrderby() {
  400. return true;
  401. }
  402. /**
  403. * Returns true if this database requires that SELECT DISTINCT queries require that all
  404. ORDER BY expressions occur in the SELECT list per the SQL92 standard
  405. *
  406. * @return bool
  407. */
  408. function standardSelectDistinct() {
  409. return true;
  410. }
  411. /**
  412. * Returns true if this database can do a native search on IP columns
  413. * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
  414. *
  415. * @return bool
  416. */
  417. function searchableIPs() {
  418. return false;
  419. }
  420. /**
  421. * Returns true if this database can use functional indexes
  422. *
  423. * @return bool
  424. */
  425. function functionalIndexes() {
  426. return false;
  427. }
  428. /**
  429. * Return the last query that went through DatabaseBase::query()
  430. * @return String
  431. */
  432. function lastQuery() {
  433. return $this->mLastQuery;
  434. }
  435. /**
  436. * Returns true if the connection may have been used for write queries.
  437. * Should return true if unsure.
  438. *
  439. * @return bool
  440. */
  441. function doneWrites() {
  442. return $this->mDoneWrites;
  443. }
  444. /**
  445. * Is a connection to the database open?
  446. * @return Boolean
  447. */
  448. function isOpen() {
  449. return $this->mOpened;
  450. }
  451. /**
  452. * Set a flag for this connection
  453. *
  454. * @param $flag Integer: DBO_* constants from Defines.php:
  455. * - DBO_DEBUG: output some debug info (same as debug())
  456. * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
  457. * - DBO_IGNORE: ignore errors (same as ignoreErrors())
  458. * - DBO_TRX: automatically start transactions
  459. * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
  460. * and removes it in command line mode
  461. * - DBO_PERSISTENT: use persistant database connection
  462. */
  463. function setFlag( $flag ) {
  464. $this->mFlags |= $flag;
  465. }
  466. /**
  467. * Clear a flag for this connection
  468. *
  469. * @param $flag: same as setFlag()'s $flag param
  470. */
  471. function clearFlag( $flag ) {
  472. $this->mFlags &= ~$flag;
  473. }
  474. /**
  475. * Returns a boolean whether the flag $flag is set for this connection
  476. *
  477. * @param $flag: same as setFlag()'s $flag param
  478. * @return Boolean
  479. */
  480. function getFlag( $flag ) {
  481. return !!( $this->mFlags & $flag );
  482. }
  483. /**
  484. * General read-only accessor
  485. *
  486. * @param $name string
  487. *
  488. * @return string
  489. */
  490. function getProperty( $name ) {
  491. return $this->$name;
  492. }
  493. /**
  494. * @return string
  495. */
  496. function getWikiID() {
  497. if ( $this->mTablePrefix ) {
  498. return "{$this->mDBname}-{$this->mTablePrefix}";
  499. } else {
  500. return $this->mDBname;
  501. }
  502. }
  503. /**
  504. * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
  505. *
  506. * @return string
  507. */
  508. public function getSchemaPath() {
  509. global $IP;
  510. if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
  511. return "$IP/maintenance/" . $this->getType() . "/tables.sql";
  512. } else {
  513. return "$IP/maintenance/tables.sql";
  514. }
  515. }
  516. # ------------------------------------------------------------------------------
  517. # Other functions
  518. # ------------------------------------------------------------------------------
  519. /**
  520. * Constructor.
  521. * @param $server String: database server host
  522. * @param $user String: database user name
  523. * @param $password String: database user password
  524. * @param $dbName String: database name
  525. * @param $flags
  526. * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
  527. */
  528. function __construct( $server = false, $user = false, $password = false, $dbName = false,
  529. $flags = 0, $tablePrefix = 'get from global'
  530. ) {
  531. global $wgDBprefix, $wgCommandLineMode;
  532. $this->mFlags = $flags;
  533. if ( $this->mFlags & DBO_DEFAULT ) {
  534. if ( $wgCommandLineMode ) {
  535. $this->mFlags &= ~DBO_TRX;
  536. } else {
  537. $this->mFlags |= DBO_TRX;
  538. }
  539. }
  540. /** Get the default table prefix*/
  541. if ( $tablePrefix == 'get from global' ) {
  542. $this->mTablePrefix = $wgDBprefix;
  543. } else {
  544. $this->mTablePrefix = $tablePrefix;
  545. }
  546. if ( $user ) {
  547. $this->open( $server, $user, $password, $dbName );
  548. }
  549. }
  550. /**
  551. * Called by serialize. Throw an exception when DB connection is serialized.
  552. * This causes problems on some database engines because the connection is
  553. * not restored on unserialize.
  554. */
  555. public function __sleep() {
  556. throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
  557. }
  558. /**
  559. * Same as new DatabaseMysql( ... ), kept for backward compatibility
  560. * @deprecated since 1.17
  561. *
  562. * @param $server
  563. * @param $user
  564. * @param $password
  565. * @param $dbName
  566. * @param $flags int
  567. * @return DatabaseMysql
  568. */
  569. static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
  570. wfDeprecated( __METHOD__, '1.17' );
  571. return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
  572. }
  573. /**
  574. * Same as new factory( ... ), kept for backward compatibility
  575. * @deprecated since 1.18
  576. * @see Database::factory()
  577. */
  578. public final static function newFromType( $dbType, $p = array() ) {
  579. wfDeprecated( __METHOD__, '1.18' );
  580. if ( isset( $p['tableprefix'] ) ) {
  581. $p['tablePrefix'] = $p['tableprefix'];
  582. }
  583. return self::factory( $dbType, $p );
  584. }
  585. /**
  586. * Given a DB type, construct the name of the appropriate child class of
  587. * DatabaseBase. This is designed to replace all of the manual stuff like:
  588. * $class = 'Database' . ucfirst( strtolower( $type ) );
  589. * as well as validate against the canonical list of DB types we have
  590. *
  591. * This factory function is mostly useful for when you need to connect to a
  592. * database other than the MediaWiki default (such as for external auth,
  593. * an extension, et cetera). Do not use this to connect to the MediaWiki
  594. * database. Example uses in core:
  595. * @see LoadBalancer::reallyOpenConnection()
  596. * @see ExternalUser_MediaWiki::initFromCond()
  597. * @see ForeignDBRepo::getMasterDB()
  598. * @see WebInstaller_DBConnect::execute()
  599. *
  600. * @param $dbType String A possible DB type
  601. * @param $p Array An array of options to pass to the constructor.
  602. * Valid options are: host, user, password, dbname, flags, tablePrefix
  603. * @return DatabaseBase subclass or null
  604. */
  605. public final static function factory( $dbType, $p = array() ) {
  606. $canonicalDBTypes = array(
  607. 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
  608. );
  609. $dbType = strtolower( $dbType );
  610. $class = 'Database' . ucfirst( $dbType );
  611. if( in_array( $dbType, $canonicalDBTypes ) || ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) ) {
  612. return new $class(
  613. isset( $p['host'] ) ? $p['host'] : false,
  614. isset( $p['user'] ) ? $p['user'] : false,
  615. isset( $p['password'] ) ? $p['password'] : false,
  616. isset( $p['dbname'] ) ? $p['dbname'] : false,
  617. isset( $p['flags'] ) ? $p['flags'] : 0,
  618. isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global'
  619. );
  620. } else {
  621. return null;
  622. }
  623. }
  624. protected function installErrorHandler() {
  625. $this->mPHPError = false;
  626. $this->htmlErrors = ini_set( 'html_errors', '0' );
  627. set_error_handler( array( $this, 'connectionErrorHandler' ) );
  628. }
  629. /**
  630. * @return bool|string
  631. */
  632. protected function restoreErrorHandler() {
  633. restore_error_handler();
  634. if ( $this->htmlErrors !== false ) {
  635. ini_set( 'html_errors', $this->htmlErrors );
  636. }
  637. if ( $this->mPHPError ) {
  638. $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
  639. $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
  640. return $error;
  641. } else {
  642. return false;
  643. }
  644. }
  645. /**
  646. * @param $errno
  647. * @param $errstr
  648. */
  649. protected function connectionErrorHandler( $errno, $errstr ) {
  650. $this->mPHPError = $errstr;
  651. }
  652. /**
  653. * Closes a database connection.
  654. * if it is open : commits any open transactions
  655. *
  656. * @return Bool operation success. true if already closed.
  657. */
  658. function close() {
  659. # Stub, should probably be overridden
  660. return true;
  661. }
  662. /**
  663. * @param $error String: fallback error message, used if none is given by DB
  664. */
  665. function reportConnectionError( $error = 'Unknown error' ) {
  666. $myError = $this->lastError();
  667. if ( $myError ) {
  668. $error = $myError;
  669. }
  670. # New method
  671. throw new DBConnectionError( $this, $error );
  672. }
  673. /**
  674. * The DBMS-dependent part of query()
  675. *
  676. * @param $sql String: SQL query.
  677. * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
  678. */
  679. protected abstract function doQuery( $sql );
  680. /**
  681. * Determine whether a query writes to the DB.
  682. * Should return true if unsure.
  683. *
  684. * @param $sql string
  685. *
  686. * @return bool
  687. */
  688. function isWriteQuery( $sql ) {
  689. return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
  690. }
  691. /**
  692. * Run an SQL query and return the result. Normally throws a DBQueryError
  693. * on failure. If errors are ignored, returns false instead.
  694. *
  695. * In new code, the query wrappers select(), insert(), update(), delete(),
  696. * etc. should be used where possible, since they give much better DBMS
  697. * independence and automatically quote or validate user input in a variety
  698. * of contexts. This function is generally only useful for queries which are
  699. * explicitly DBMS-dependent and are unsupported by the query wrappers, such
  700. * as CREATE TABLE.
  701. *
  702. * However, the query wrappers themselves should call this function.
  703. *
  704. * @param $sql String: SQL query
  705. * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
  706. * comment (you can use __METHOD__ or add some extra info)
  707. * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
  708. * maybe best to catch the exception instead?
  709. * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
  710. * for a successful read query, or false on failure if $tempIgnore set
  711. * @throws DBQueryError Thrown when the database returns an error of any kind
  712. */
  713. public function query( $sql, $fname = '', $tempIgnore = false ) {
  714. $isMaster = !is_null( $this->getLBInfo( 'master' ) );
  715. if ( !Profiler::instance()->isStub() ) {
  716. # generalizeSQL will probably cut down the query to reasonable
  717. # logging size most of the time. The substr is really just a sanity check.
  718. if ( $isMaster ) {
  719. $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
  720. $totalProf = 'DatabaseBase::query-master';
  721. } else {
  722. $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
  723. $totalProf = 'DatabaseBase::query';
  724. }
  725. wfProfileIn( $totalProf );
  726. wfProfileIn( $queryProf );
  727. }
  728. $this->mLastQuery = $sql;
  729. if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
  730. # Set a flag indicating that writes have been done
  731. wfDebug( __METHOD__ . ": Writes done: $sql\n" );
  732. $this->mDoneWrites = true;
  733. }
  734. # Add a comment for easy SHOW PROCESSLIST interpretation
  735. global $wgUser;
  736. if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
  737. $userName = $wgUser->getName();
  738. if ( mb_strlen( $userName ) > 15 ) {
  739. $userName = mb_substr( $userName, 0, 15 ) . '...';
  740. }
  741. $userName = str_replace( '/', '', $userName );
  742. } else {
  743. $userName = '';
  744. }
  745. $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
  746. # If DBO_TRX is set, start a transaction
  747. if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
  748. $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
  749. # avoid establishing transactions for SHOW and SET statements too -
  750. # that would delay transaction initializations to once connection
  751. # is really used by application
  752. $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
  753. if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 )
  754. $this->begin( __METHOD__ . " ($fname)" );
  755. }
  756. if ( $this->debug() ) {
  757. static $cnt = 0;
  758. $cnt++;
  759. $sqlx = substr( $commentedSql, 0, 500 );
  760. $sqlx = strtr( $sqlx, "\t\n", ' ' );
  761. $master = $isMaster ? 'master' : 'slave';
  762. wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
  763. }
  764. if ( istainted( $sql ) & TC_MYSQL ) {
  765. throw new MWException( 'Tainted query found' );
  766. }
  767. $queryId = MWDebug::query( $sql, $fname, $isMaster );
  768. # Do the query and handle errors
  769. $ret = $this->doQuery( $commentedSql );
  770. MWDebug::queryTime( $queryId );
  771. # Try reconnecting if the connection was lost
  772. if ( false === $ret && $this->wasErrorReissuable() ) {
  773. # Transaction is gone, like it or not
  774. $this->mTrxLevel = 0;
  775. wfDebug( "Connection lost, reconnecting...\n" );
  776. if ( $this->ping() ) {
  777. wfDebug( "Reconnected\n" );
  778. $sqlx = substr( $commentedSql, 0, 500 );
  779. $sqlx = strtr( $sqlx, "\t\n", ' ' );
  780. global $wgRequestTime;
  781. $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
  782. if ( $elapsed < 300 ) {
  783. # Not a database error to lose a transaction after a minute or two
  784. wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
  785. }
  786. $ret = $this->doQuery( $commentedSql );
  787. } else {
  788. wfDebug( "Failed\n" );
  789. }
  790. }
  791. if ( false === $ret ) {
  792. $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
  793. }
  794. if ( !Profiler::instance()->isStub() ) {
  795. wfProfileOut( $queryProf );
  796. wfProfileOut( $totalProf );
  797. }
  798. return $this->resultObject( $ret );
  799. }
  800. /**
  801. * Report a query error. Log the error, and if neither the object ignore
  802. * flag nor the $tempIgnore flag is set, throw a DBQueryError.
  803. *
  804. * @param $error String
  805. * @param $errno Integer
  806. * @param $sql String
  807. * @param $fname String
  808. * @param $tempIgnore Boolean
  809. */
  810. function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
  811. # Ignore errors during error handling to avoid infinite recursion
  812. $ignore = $this->ignoreErrors( true );
  813. ++$this->mErrorCount;
  814. if ( $ignore || $tempIgnore ) {
  815. wfDebug( "SQL ERROR (ignored): $error\n" );
  816. $this->ignoreErrors( $ignore );
  817. } else {
  818. $sql1line = str_replace( "\n", "\\n", $sql );
  819. wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
  820. wfDebug( "SQL ERROR: " . $error . "\n" );
  821. throw new DBQueryError( $this, $error, $errno, $sql, $fname );
  822. }
  823. }
  824. /**
  825. * Intended to be compatible with the PEAR::DB wrapper functions.
  826. * http://pear.php.net/manual/en/package.database.db.intro-execute.php
  827. *
  828. * ? = scalar value, quoted as necessary
  829. * ! = raw SQL bit (a function for instance)
  830. * & = filename; reads the file and inserts as a blob
  831. * (we don't use this though...)
  832. *
  833. * This function should not be used directly by new code outside of the
  834. * database classes. The query wrapper functions (select() etc.) should be
  835. * used instead.
  836. *
  837. * @param $sql string
  838. * @param $func string
  839. *
  840. * @return array
  841. */
  842. function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
  843. /* MySQL doesn't support prepared statements (yet), so just
  844. pack up the query for reference. We'll manually replace
  845. the bits later. */
  846. return array( 'query' => $sql, 'func' => $func );
  847. }
  848. /**
  849. * Free a prepared query, generated by prepare().
  850. * @param $prepared
  851. */
  852. function freePrepared( $prepared ) {
  853. /* No-op by default */
  854. }
  855. /**
  856. * Execute a prepared query with the various arguments
  857. * @param $prepared String: the prepared sql
  858. * @param $args Mixed: Either an array here, or put scalars as varargs
  859. *
  860. * @return ResultWrapper
  861. */
  862. function execute( $prepared, $args = null ) {
  863. if ( !is_array( $args ) ) {
  864. # Pull the var args
  865. $args = func_get_args();
  866. array_shift( $args );
  867. }
  868. $sql = $this->fillPrepared( $prepared['query'], $args );
  869. return $this->query( $sql, $prepared['func'] );
  870. }
  871. /**
  872. * Prepare & execute an SQL statement, quoting and inserting arguments
  873. * in the appropriate places.
  874. *
  875. * This function should not be used directly by new code outside of the
  876. * database classes. The query wrapper functions (select() etc.) should be
  877. * used instead.
  878. *
  879. * @param $query String
  880. * @param $args ...
  881. *
  882. * @return ResultWrapper
  883. */
  884. function safeQuery( $query, $args = null ) {
  885. $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
  886. if ( !is_array( $args ) ) {
  887. # Pull the var args
  888. $args = func_get_args();
  889. array_shift( $args );
  890. }
  891. $retval = $this->execute( $prepared, $args );
  892. $this->freePrepared( $prepared );
  893. return $retval;
  894. }
  895. /**
  896. * For faking prepared SQL statements on DBs that don't support
  897. * it directly.
  898. * @param $preparedQuery String: a 'preparable' SQL statement
  899. * @param $args Array of arguments to fill it with
  900. * @return string executable SQL
  901. */
  902. function fillPrepared( $preparedQuery, $args ) {
  903. reset( $args );
  904. $this->preparedArgs =& $args;
  905. return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
  906. array( &$this, 'fillPreparedArg' ), $preparedQuery );
  907. }
  908. /**
  909. * preg_callback func for fillPrepared()
  910. * The arguments should be in $this->preparedArgs and must not be touched
  911. * while we're doing this.
  912. *
  913. * @param $matches Array
  914. * @return String
  915. */
  916. function fillPreparedArg( $matches ) {
  917. switch( $matches[1] ) {
  918. case '\\?': return '?';
  919. case '\\!': return '!';
  920. case '\\&': return '&';
  921. }
  922. list( /* $n */ , $arg ) = each( $this->preparedArgs );
  923. switch( $matches[1] ) {
  924. case '?': return $this->addQuotes( $arg );
  925. case '!': return $arg;
  926. case '&':
  927. # return $this->addQuotes( file_get_contents( $arg ) );
  928. throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
  929. default:
  930. throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
  931. }
  932. }
  933. /**
  934. * Free a result object returned by query() or select(). It's usually not
  935. * necessary to call this, just use unset() or let the variable holding
  936. * the result object go out of scope.
  937. *
  938. * @param $res Mixed: A SQL result
  939. */
  940. function freeResult( $res ) {
  941. }
  942. /**
  943. * Simple UPDATE wrapper.
  944. * Usually throws a DBQueryError on failure.
  945. * If errors are explicitly ignored, returns success
  946. *
  947. * This function exists for historical reasons, DatabaseBase::update() has a more standard
  948. * calling convention and feature set
  949. *
  950. * @param $table string
  951. * @param $var
  952. * @param $value
  953. * @param $cond
  954. * @param $fname string
  955. *
  956. * @return bool
  957. */
  958. function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
  959. $table = $this->tableName( $table );
  960. $sql = "UPDATE $table SET $var = '" .
  961. $this->strencode( $value ) . "' WHERE ($cond)";
  962. return (bool)$this->query( $sql, $fname );
  963. }
  964. /**
  965. * A SELECT wrapper which returns a single field from a single result row.
  966. *
  967. * Usually throws a DBQueryError on failure. If errors are explicitly
  968. * ignored, returns false on failure.
  969. *
  970. * If no result rows are returned from the query, false is returned.
  971. *
  972. * @param $table string|array Table name. See DatabaseBase::select() for details.
  973. * @param $var string The field name to select. This must be a valid SQL
  974. * fragment: do not use unvalidated user input.
  975. * @param $cond string|array The condition array. See DatabaseBase::select() for details.
  976. * @param $fname string The function name of the caller.
  977. * @param $options string|array The query options. See DatabaseBase::select() for details.
  978. *
  979. * @return false|mixed The value from the field, or false on failure.
  980. */
  981. function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
  982. $options = array() )
  983. {
  984. if ( !is_array( $options ) ) {
  985. $options = array( $options );
  986. }
  987. $options['LIMIT'] = 1;
  988. $res = $this->select( $table, $var, $cond, $fname, $options );
  989. if ( $res === false || !$this->numRows( $res ) ) {
  990. return false;
  991. }
  992. $row = $this->fetchRow( $res );
  993. if ( $row !== false ) {
  994. return reset( $row );
  995. } else {
  996. return false;
  997. }
  998. }
  999. /**
  1000. * Returns an optional USE INDEX clause to go after the table, and a
  1001. * string to go at the end of the query.
  1002. *
  1003. * @param $options Array: associative array of options to be turned into
  1004. * an SQL query, valid keys are listed in the function.
  1005. * @return Array
  1006. * @see DatabaseBase::select()
  1007. */
  1008. function makeSelectOptions( $options ) {
  1009. $preLimitTail = $postLimitTail = '';
  1010. $startOpts = '';
  1011. $noKeyOptions = array();
  1012. foreach ( $options as $key => $option ) {
  1013. if ( is_numeric( $key ) ) {
  1014. $noKeyOptions[$option] = true;
  1015. }
  1016. }
  1017. if ( isset( $options['GROUP BY'] ) ) {
  1018. $gb = is_array( $options['GROUP BY'] )
  1019. ? implode( ',', $options['GROUP BY'] )
  1020. : $options['GROUP BY'];
  1021. $preLimitTail .= " GROUP BY {$gb}";
  1022. }
  1023. if ( isset( $options['HAVING'] ) ) {
  1024. $preLimitTail .= " HAVING {$options['HAVING']}";
  1025. }
  1026. if ( isset( $options['ORDER BY'] ) ) {
  1027. $ob = is_array( $options['ORDER BY'] )
  1028. ? implode( ',', $options['ORDER BY'] )
  1029. : $options['ORDER BY'];
  1030. $preLimitTail .= " ORDER BY {$ob}";
  1031. }
  1032. // if (isset($options['LIMIT'])) {
  1033. // $tailOpts .= $this->limitResult('', $options['LIMIT'],
  1034. // isset($options['OFFSET']) ? $options['OFFSET']
  1035. // : false);
  1036. // }
  1037. if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
  1038. $postLimitTail .= ' FOR UPDATE';
  1039. }
  1040. if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
  1041. $postLimitTail .= ' LOCK IN SHARE MODE';
  1042. }
  1043. if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
  1044. $startOpts .= 'DISTINCT';
  1045. }
  1046. # Various MySQL extensions
  1047. if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
  1048. $startOpts .= ' /*! STRAIGHT_JOIN */';
  1049. }
  1050. if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
  1051. $startOpts .= ' HIGH_PRIORITY';
  1052. }
  1053. if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
  1054. $startOpts .= ' SQL_BIG_RESULT';
  1055. }
  1056. if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
  1057. $startOpts .= ' SQL_BUFFER_RESULT';
  1058. }
  1059. if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
  1060. $startOpts .= ' SQL_SMALL_RESULT';
  1061. }
  1062. if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
  1063. $startOpts .= ' SQL_CALC_FOUND_ROWS';
  1064. }
  1065. if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
  1066. $startOpts .= ' SQL_CACHE';
  1067. }
  1068. if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
  1069. $startOpts .= ' SQL_NO_CACHE';
  1070. }
  1071. if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
  1072. $useIndex = $this->useIndexClause( $options['USE INDEX'] );
  1073. } else {
  1074. $useIndex = '';
  1075. }
  1076. return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
  1077. }
  1078. /**
  1079. * Execute a SELECT query constructed using the various parameters provided.
  1080. * See below for full details of the parameters.
  1081. *
  1082. * @param $table String|Array Table name
  1083. * @param $vars String|Array Field names
  1084. * @param $conds String|Array Conditions
  1085. * @param $fname String Caller function name
  1086. * @param $options Array Query options
  1087. * @param $join_conds Array Join conditions
  1088. *
  1089. * @param $table string|array
  1090. *
  1091. * May be either an array of table names, or a single string holding a table
  1092. * name. If an array is given, table aliases can be specified, for example:
  1093. *
  1094. * array( 'a' => 'user' )
  1095. *
  1096. * This includes the user table in the query, with the alias "a" available
  1097. * for use in field names (e.g. a.user_name).
  1098. *
  1099. * All of the table names given here are automatically run through
  1100. * DatabaseBase::tableName(), which causes the table prefix (if any) to be
  1101. * added, and various other table name mappings to be performed.
  1102. *
  1103. *
  1104. * @param $vars string|array
  1105. *
  1106. * May be either a field name or an array of field names. The field names
  1107. * here are complete fragments of SQL, for direct inclusion into the SELECT
  1108. * query. Expressions and aliases may be specified as in SQL, for example:
  1109. *
  1110. * array( 'MAX(rev_id) AS maxrev' )
  1111. *
  1112. * If an expression is given, care must be taken to ensure that it is
  1113. * DBMS-independent.
  1114. *
  1115. *
  1116. * @param $conds string|array
  1117. *
  1118. * May be either a string containing a single condition, or an array of
  1119. * conditions. If an array is given, the conditions constructed from each
  1120. * element are combined with AND.
  1121. *
  1122. * Array elements may take one of two forms:
  1123. *
  1124. * - Elements with a numeric key are interpreted as raw SQL fragments.
  1125. * - Elements with a string key are interpreted as equality conditions,
  1126. * where the key is the field name.
  1127. * - If the value of such an array element is a scalar (such as a
  1128. * string), it will be treated as data and thus quoted appropriately.
  1129. * If it is null, an IS NULL clause will be added.
  1130. * - If the value is an array, an IN(...) clause will be constructed,
  1131. * such that the field name may match any of the elements in the
  1132. * array. The elements of the array will be quoted.
  1133. *
  1134. * Note that expressions are often DBMS-dependent in their syntax.
  1135. * DBMS-independent wrappers are provided for constructing several types of
  1136. * expression commonly used in condition queries. See:
  1137. * - DatabaseBase::buildLike()
  1138. * - DatabaseBase::conditional()
  1139. *
  1140. *
  1141. * @param $options string|array
  1142. *
  1143. * Optional: Array of query options. Boolean options are specified by
  1144. * including them in the array as a string value with a numeric key, for
  1145. * example:
  1146. *
  1147. * array( 'FOR UPDATE' )
  1148. *
  1149. * The supported options are:
  1150. *
  1151. * - OFFSET: Skip this many rows at the start of the result set. OFFSET
  1152. * with LIMIT can theoretically be used for paging through a result set,
  1153. * but this is discouraged in MediaWiki for performance reasons.
  1154. *
  1155. * - LIMIT: Integer: return at most this many rows. The rows are sorted
  1156. * and then the first rows are taken until the limit is reached. LIMIT
  1157. * is applied to a result set after OFFSET.
  1158. *
  1159. * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
  1160. * changed until the next COMMIT.
  1161. *
  1162. * - DISTINCT: Boolean: return only unique result rows.
  1163. *
  1164. * - GROUP BY: May be either an SQL fragment string naming a field or
  1165. * expression to group by, or an array of such SQL fragments.
  1166. *
  1167. * - HAVING: A string containing a HAVING clause.
  1168. *
  1169. * - ORDER BY: May be either an SQL fragment giving a field name or
  1170. * expression to order by, or an array of such SQL fragments.
  1171. *
  1172. * - USE INDEX: This may be either a string giving the index name to use
  1173. * for the query, or an array. If it is an associative array, each key
  1174. * gives the table name (or alias), each value gives the index name to
  1175. * use for that table. All strings are SQL fragments and so should be
  1176. * validated by the caller.
  1177. *
  1178. * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
  1179. * instead of SELECT.
  1180. *
  1181. * And also the following boolean MySQL extensions, see the MySQL manual
  1182. * for documentation:
  1183. *
  1184. * - LOCK IN SHARE MODE
  1185. * - STRAIGHT_JOIN
  1186. * - HIGH_PRIORITY
  1187. * - SQL_BIG_RESULT
  1188. * - SQL_BUFFER_RESULT
  1189. * - SQL_SMALL_RESULT
  1190. * - SQL_CALC_FOUND_ROWS
  1191. * - SQL_CACHE
  1192. * - SQL_NO_CACHE
  1193. *
  1194. *
  1195. * @param $join_conds string|array
  1196. *
  1197. * Optional associative array of table-specific join conditions. In the
  1198. * most common case, this is unnecessary, since the join condition can be
  1199. * in $conds. However, it is useful for doing a LEFT JOIN.
  1200. *
  1201. * The key of the array contains the table name or alias. The value is an
  1202. * array with two elements, numbered 0 and 1. The first gives the type of
  1203. * join, the second is an SQL fragment giving the join condition for that
  1204. * table. For example:
  1205. *
  1206. * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
  1207. *
  1208. * @return ResultWrapper. If the query returned no rows, a ResultWrapper
  1209. * with no rows in it will be returned. If there was a query error, a
  1210. * DBQueryError exception will be thrown, except if the "ignore errors"
  1211. * option was set, in which case false will be returned.
  1212. */
  1213. function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
  1214. $options = array(), $join_conds = array() ) {
  1215. $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
  1216. return $this->query( $sql, $fname );
  1217. }
  1218. /**
  1219. * The equivalent of DatabaseBase::select() except that the constructed SQL
  1220. * is returned, instead of being immediately executed.
  1221. *
  1222. * @param $table string|array Table name
  1223. * @param $vars string|array Field names
  1224. * @param $conds string|array Conditions
  1225. * @param $fname string Caller function name
  1226. * @param $options string|array Query options
  1227. * @param $join_conds string|array Join conditions
  1228. *
  1229. * @return SQL query string.
  1230. * @see DatabaseBase::select()
  1231. */
  1232. function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
  1233. if ( is_array( $vars ) ) {
  1234. $vars = implode( ',', $vars );
  1235. }
  1236. $options = (array)$options;
  1237. if ( is_array( $table ) ) {
  1238. $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
  1239. ? $options['USE INDEX']
  1240. : array();
  1241. if ( count( $join_conds ) || count( $useIndex ) ) {
  1242. $from = ' FROM ' .
  1243. $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
  1244. } else {
  1245. $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
  1246. }
  1247. } elseif ( $table != '' ) {
  1248. if ( $table[0] == ' ' ) {
  1249. $from = ' FROM ' . $table;
  1250. } else {
  1251. $from = ' FROM ' . $this->tableName( $table );
  1252. }
  1253. } else {
  1254. $from = '';
  1255. }
  1256. list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
  1257. if ( !empty( $conds ) ) {
  1258. if ( is_array( $conds ) ) {
  1259. $conds = $this->makeList( $conds, LIST_AND );
  1260. }
  1261. $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
  1262. } else {
  1263. $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
  1264. }
  1265. if ( isset( $options['LIMIT'] ) ) {
  1266. $sql = $this->limitResult( $sql, $options['LIMIT'],
  1267. isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
  1268. }
  1269. $sql = "$sql $postLimitTail";
  1270. if ( isset( $options['EXPLAIN'] ) ) {
  1271. $sql = 'EXPLAIN ' . $sql;
  1272. }
  1273. return $sql;
  1274. }
  1275. /**
  1276. * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
  1277. * that a single row object is returned. If the query returns no rows,
  1278. * false is returned.
  1279. *
  1280. * @param $table string|array Table name
  1281. * @param $vars string|array Field names
  1282. * @param $conds array Conditions
  1283. * @param $fname string Caller function name
  1284. * @param $options string|array Query options
  1285. * @param $join_conds array|string Join conditions
  1286. *
  1287. * @return ResultWrapper|bool
  1288. */
  1289. function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
  1290. $options = array(), $join_conds = array() )
  1291. {
  1292. $options = (array)$options;
  1293. $options['LIMIT'] = 1;
  1294. $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
  1295. if ( $res === false ) {
  1296. return false;
  1297. }
  1298. if ( !$this->numRows( $res ) ) {
  1299. return false;
  1300. }
  1301. $obj = $this->fetchObject( $res );
  1302. return $obj;
  1303. }
  1304. /**
  1305. * Estimate rows in dataset.
  1306. *
  1307. * MySQL allows you to estimate the number of rows that would be returned
  1308. * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
  1309. * index cardinality statistics, and is notoriously inaccurate, especially
  1310. * when large numbers of rows have recently been added or deleted.
  1311. *
  1312. * For DBMSs that don't support fast result size estimation, this function
  1313. * will actually perform the SELECT COUNT(*).
  1314. *
  1315. * Takes the same arguments as DatabaseBase::select().
  1316. *
  1317. * @param $table String: table name
  1318. * @param Array|string $vars : unused
  1319. * @param Array|string $conds : filters on the table
  1320. * @param $fname String: function name for profiling
  1321. * @param $options Array: options for select
  1322. * @return Integer: row count
  1323. */
  1324. public function estimateRowCount( $table, $vars = '*', $conds = '',
  1325. $fname = 'DatabaseBase::estimateRowCount', $options = array() )
  1326. {
  1327. $rows = 0;
  1328. $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
  1329. if ( $res ) {
  1330. $row = $this->fetchRow( $res );
  1331. $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
  1332. }
  1333. return $rows;
  1334. }
  1335. /**
  1336. * Removes most variables from an SQL query and replaces them with X or N for numbers.
  1337. * It's only slightly flawed. Don't use for anything important.
  1338. *
  1339. * @param $sql String A SQL Query
  1340. *
  1341. * @return string
  1342. */
  1343. static function generalizeSQL( $sql ) {
  1344. # This does the same as the regexp below would do, but in such a way
  1345. # as to avoid crashing php on some large strings.
  1346. # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
  1347. $sql = str_replace ( "\\\\", '', $sql );
  1348. $sql = str_replace ( "\\'", '', $sql );
  1349. $sql = str_replace ( "\\\"", '', $sql );
  1350. $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
  1351. $sql = preg_replace ( '/".*"/s', "'X'", $sql );
  1352. # All newlines, tabs, etc replaced by single space
  1353. $sql = preg_replace ( '/\s+/', ' ', $sql );
  1354. # All numbers => N
  1355. $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
  1356. return $sql;
  1357. }
  1358. /**
  1359. * Determines whether a field exists in a table
  1360. *
  1361. * @param $table String: table name
  1362. * @param $field String: filed to check on that table
  1363. * @param $fname String: calling function name (optional)
  1364. * @return Boolean: whether $table has filed $field
  1365. */
  1366. function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
  1367. $info = $this->fieldInfo( $table, $field );
  1368. return (bool)$info;
  1369. }
  1370. /**
  1371. * Determines whether an index exists
  1372. * Usually throws a DBQueryError on failure
  1373. * If errors are explicitly ignored, returns NULL on failure
  1374. *
  1375. * @param $table
  1376. * @param $index
  1377. * @param $fname string
  1378. *
  1379. * @return bool|null
  1380. */
  1381. function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
  1382. $info = $this->indexInfo( $table, $index, $fname );
  1383. if ( is_null( $info ) ) {
  1384. return null;
  1385. } else {
  1386. return $info !== false;
  1387. }
  1388. }
  1389. /**
  1390. * Query whether a given table exists
  1391. *
  1392. * @param $table string
  1393. * @param $fname string
  1394. *
  1395. * @return bool
  1396. */
  1397. function tableExists( $table, $fname = __METHOD__ ) {
  1398. $table = $this->tableName( $table );
  1399. $old = $this->ignoreErrors( true );
  1400. $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
  1401. $this->ignoreErrors( $old );
  1402. return (bool)$res;
  1403. }
  1404. /**
  1405. * mysql_field_type() wrapper
  1406. * @param $res
  1407. * @param $index
  1408. * @return string
  1409. */
  1410. function fieldType( $res, $index ) {
  1411. if ( $res instanceof ResultWrapper ) {
  1412. $res = $res->result;
  1413. }
  1414. return mysql_field_type( $res, $index );
  1415. }
  1416. /**
  1417. * Determines if a given index is unique
  1418. *
  1419. * @param $table string
  1420. * @param $index string
  1421. *
  1422. * @return bool
  1423. */
  1424. function indexUnique( $table, $index ) {
  1425. $indexInfo = $this->indexInfo( $table, $index );
  1426. if ( !$indexInfo ) {
  1427. return null;
  1428. }
  1429. return !$indexInfo[0]->Non_unique;
  1430. }
  1431. /**
  1432. * Helper for DatabaseBase::insert().
  1433. *
  1434. * @param $options array
  1435. * @return string
  1436. */
  1437. function makeInsertOptions( $options ) {
  1438. return implode( ' ', $options );
  1439. }
  1440. /**
  1441. * INSERT wrapper, inserts an array into a table.
  1442. *
  1443. * $a may be either:
  1444. *
  1445. * - A single associative array. The array keys are the field names, and
  1446. * the values are the values to insert. The values are treated as data
  1447. * and will be quoted appropriately. If NULL is inserted, this will be
  1448. * converted to a database NULL.
  1449. * - An array with numeric keys, holding a list of associative arrays.
  1450. * This causes a multi-row INSERT on DBMSs that support it. The keys in
  1451. * each subarray must be identical to each other, and in the same order.
  1452. *
  1453. * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
  1454. * returns success.
  1455. *
  1456. * $options is an array of options, with boolean options encoded as values
  1457. * with numeric keys, in the same style as $options in
  1458. * DatabaseBase::select(). Supported options are:
  1459. *
  1460. * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
  1461. * any rows which cause duplicate key errors are not inserted. It's
  1462. * possible to determine how many rows were successfully inserted using
  1463. * DatabaseBase::affectedRows().
  1464. *
  1465. * @param $table String Table name. This will be passed through
  1466. * DatabaseBase::tableName().
  1467. * @param $a Array of rows to insert
  1468. * @param $fname String Calling function name (use __METHOD__) for logs/profiling
  1469. * @param $options Array of options
  1470. *
  1471. * @return bool
  1472. */
  1473. function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
  1474. # No rows to insert, easy just return now
  1475. if ( !count( $a ) ) {
  1476. return true;
  1477. }
  1478. $table = $this->tableName( $table );
  1479. if ( !is_array( $options ) ) {
  1480. $options = array( $options );
  1481. }
  1482. $options = $this->makeInsertOptions( $options );
  1483. if ( isset( $a[0] ) && is_array( $a[0] ) ) {
  1484. $multi = true;
  1485. $keys = array_keys( $a[0] );
  1486. } else {
  1487. $multi = false;
  1488. $keys = array_keys( $a );
  1489. }
  1490. $sql = 'INSERT ' . $options .
  1491. " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
  1492. if ( $multi ) {
  1493. $first = true;
  1494. foreach ( $a as $row ) {
  1495. if ( $first ) {
  1496. $first = false;
  1497. } else {
  1498. $sql .= ',';
  1499. }
  1500. $sql .= '(' . $this->makeList( $row ) . ')';
  1501. }
  1502. } else {
  1503. $sql .= '(' . $this->makeList( $a ) . ')';
  1504. }
  1505. return (bool)$this->query( $sql, $fname );
  1506. }
  1507. /**
  1508. * Make UPDATE options for the DatabaseBase::update function
  1509. *
  1510. * @param $options Array: The options passed to DatabaseBase::update
  1511. * @return string
  1512. */
  1513. function makeUpdateOptions( $options ) {
  1514. if ( !is_array( $options ) ) {
  1515. $options = array( $options );
  1516. }
  1517. $opts = array();
  1518. if ( in_array( 'LOW_PRIORITY', $options ) ) {
  1519. $opts[] = $this->lowPriorityOption();
  1520. }
  1521. if ( in_array( 'IGNORE', $options ) ) {
  1522. $opts[] = 'IGNORE';
  1523. }
  1524. return implode( ' ', $opts );
  1525. }
  1526. /**
  1527. * UPDATE wrapper. Takes a condition array and a SET array.
  1528. *
  1529. * @param $table String name of the table to UPDATE. This will be passed through
  1530. * DatabaseBase::tableName().
  1531. *
  1532. * @param $values Array: An array of values to SET. For each array element,
  1533. * the key gives the field name, and the value gives the data
  1534. * to set that field to. The data will be quoted by
  1535. * DatabaseBase::addQuotes().
  1536. *
  1537. * @param $conds Array: An array of conditions (WHERE). See
  1538. * DatabaseBase::select() for the details of the format of
  1539. * condition arrays. Use '*' to update all rows.
  1540. *
  1541. * @param $fname String: The function name of the caller (from __METHOD__),
  1542. * for logging and profiling.
  1543. *
  1544. * @param $options Array: An array of UPDATE options, can be:
  1545. * - IGNORE: Ignore unique key conflicts
  1546. * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
  1547. * @return Boolean
  1548. */
  1549. function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
  1550. $table = $this->tableName( $table );
  1551. $opts = $this->makeUpdateOptions( $options );
  1552. $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
  1553. if ( $conds !== array() && $conds !== '*' ) {
  1554. $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
  1555. }
  1556. return $this->query( $sql, $fname );
  1557. }
  1558. /**
  1559. * Makes an encoded list of strings from an array
  1560. * @param $a Array containing the data
  1561. * @param $mode int Constant
  1562. * - LIST_COMMA: comma separated, no field names
  1563. * - LIST_AND: ANDed WHERE clause (without the WHERE). See
  1564. * the documentation for $conds in DatabaseBase::select().
  1565. * - LIST_OR: ORed WHERE clause (without the WHERE)
  1566. * - LIST_SET: comma separated with field names, like a SET clause
  1567. * - LIST_NAMES: comma separated field names
  1568. *
  1569. * @return string
  1570. */
  1571. function makeList( $a, $mode = LIST_COMMA ) {
  1572. if ( !is_array( $a ) ) {
  1573. throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
  1574. }
  1575. $first = true;
  1576. $list = '';
  1577. foreach ( $a as $field => $value ) {
  1578. if ( !$first ) {
  1579. if ( $mode == LIST_AND ) {
  1580. $list .= ' AND ';
  1581. } elseif ( $mode == LIST_OR ) {
  1582. $list .= ' OR ';
  1583. } else {
  1584. $list .= ',';
  1585. }
  1586. } else {
  1587. $first = false;
  1588. }
  1589. if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
  1590. $list .= "($value)";
  1591. } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
  1592. $list .= "$value";
  1593. } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
  1594. if ( count( $value ) == 0 ) {
  1595. throw new MWException( __METHOD__ . ': empty input' );
  1596. } elseif ( count( $value ) == 1 ) {
  1597. // Special-case single values, as IN isn't terribly efficient
  1598. // Don't necessarily assume the single key is 0; we don't
  1599. // enforce linear numeric ordering on other arrays here.
  1600. $value = array_values( $value );
  1601. $list .= $field . " = " . $this->addQuotes( $value[0] );
  1602. } else {
  1603. $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
  1604. }
  1605. } elseif ( $value === null ) {
  1606. if ( $mode == LIST_AND || $mode == LIST_OR ) {
  1607. $list .= "$field IS ";
  1608. } elseif ( $mode == LIST_SET ) {
  1609. $list .= "$field = ";
  1610. }
  1611. $list .= 'NULL';
  1612. } else {
  1613. if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
  1614. $list .= "$field = ";
  1615. }
  1616. $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
  1617. }
  1618. }
  1619. return $list;
  1620. }
  1621. /**
  1622. * Build a partial where clause from a 2-d array such as used for LinkBatch.
  1623. * The keys on each level may be either integers or strings.
  1624. *
  1625. * @param $data Array: organized as 2-d
  1626. * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
  1627. * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
  1628. * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
  1629. * @return Mixed: string SQL fragment, or false if no items in array.
  1630. */
  1631. function makeWhereFrom2d( $data, $baseKey, $subKey ) {
  1632. $conds = array();
  1633. foreach ( $data as $base => $sub ) {
  1634. if ( count( $sub ) ) {
  1635. $conds[] = $this->makeList(
  1636. array( $baseKey => $base, $subKey => array_keys( $sub ) ),
  1637. LIST_AND );
  1638. }
  1639. }
  1640. if ( $conds ) {
  1641. return $this->makeList( $conds, LIST_OR );
  1642. } else {
  1643. // Nothing to search for...
  1644. return false;
  1645. }
  1646. }
  1647. /**
  1648. * Bitwise operations
  1649. */
  1650. /**
  1651. * @param $field
  1652. * @return string
  1653. */
  1654. function bitNot( $field ) {
  1655. return "(~$field)";
  1656. }
  1657. /**
  1658. * @param $fieldLeft
  1659. * @param $fieldRight
  1660. * @return string
  1661. */
  1662. function bitAnd( $fieldLeft, $fieldRight ) {
  1663. return "($fieldLeft & $fieldRight)";
  1664. }
  1665. /**
  1666. * @param $fieldLeft
  1667. * @param $fieldRight
  1668. * @return string
  1669. */
  1670. function bitOr( $fieldLeft, $fieldRight ) {
  1671. return "($fieldLeft | $fieldRight)";
  1672. }
  1673. /**
  1674. * Change the current database
  1675. *
  1676. * @todo Explain what exactly will fail if this is not overridden.
  1677. *
  1678. * @param $db
  1679. *
  1680. * @return bool Success or failure
  1681. */
  1682. function selectDB( $db ) {
  1683. # Stub. Shouldn't cause serious problems if it's not overridden, but
  1684. # if your database engine supports a concept similar to MySQL's
  1685. # databases you may as well.
  1686. $this->mDBname = $db;
  1687. return true;
  1688. }
  1689. /**
  1690. * Get the current DB name
  1691. */
  1692. function getDBname() {
  1693. return $this->mDBname;
  1694. }
  1695. /**
  1696. * Get the server hostname or IP address
  1697. */
  1698. function getServer() {
  1699. return $this->mServer;
  1700. }
  1701. /**
  1702. * Format a table name ready for use in constructing an SQL query
  1703. *
  1704. * This does two important things: it quotes the table names to clean them up,
  1705. * and it adds a table prefix if only given a table name with no quotes.
  1706. *
  1707. * All functions of this object which require a table name call this function
  1708. * themselves. Pass the canonical name to such functions. This is only needed
  1709. * when calling query() directly.
  1710. *
  1711. * @param $name String: database table name
  1712. * @param $format String One of:
  1713. * quoted - Automatically pass the table name through addIdentifierQuotes()
  1714. * so that it can be used in a query.
  1715. * raw - Do not add identifier quotes to the table name
  1716. * @return String: full database name
  1717. */
  1718. function tableName( $name, $format = 'quoted' ) {
  1719. global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
  1720. # Skip the entire process when we have a string quoted on both ends.
  1721. # Note that we check the end so that we will still quote any use of
  1722. # use of `database`.table. But won't break things if someone wants
  1723. # to query a database table with a dot in the name.
  1724. if ( $this->isQuotedIdentifier( $name ) ) {
  1725. return $name;
  1726. }
  1727. # Lets test for any bits of text that should never show up in a table
  1728. # name. Basically anything like JOIN or ON which are actually part of
  1729. # SQL queries, but may end up inside of the table value to combine
  1730. # sql. Such as how the API is doing.
  1731. # Note that we use a whitespace test rather than a \b test to avoid
  1732. # any remote case where a word like on may be inside of a table name
  1733. # surrounded by symbols which may be considered word breaks.
  1734. if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
  1735. return $name;
  1736. }
  1737. # Split database and table into proper variables.
  1738. # We reverse the explode so that database.table and table both output
  1739. # the correct table.
  1740. $dbDetails = array_reverse( explode( '.', $name, 2 ) );
  1741. if ( isset( $dbDetails[1] ) ) {
  1742. list( $table, $database ) = $dbDetails;
  1743. } else {
  1744. list( $table ) = $dbDetails;
  1745. }
  1746. $prefix = $this->mTablePrefix; # Default prefix
  1747. # A database name has been specified in input. We don't want any
  1748. # prefixes added.
  1749. if ( isset( $database ) ) {
  1750. $prefix = '';
  1751. }
  1752. # Note that we use the long format because php will complain in in_array if
  1753. # the input is not an array, and will complain in is_array if it is not set.
  1754. if ( !isset( $database ) # Don't use shared database if pre selected.
  1755. && isset( $wgSharedDB ) # We have a shared database
  1756. && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
  1757. && isset( $wgSharedTables )
  1758. && is_array( $wgSharedTables )
  1759. && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
  1760. $database = $wgSharedDB;
  1761. $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
  1762. }
  1763. # Quote the $database and $table and apply the prefix if not quoted.
  1764. if ( isset( $database ) ) {
  1765. if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
  1766. $database = $this->addIdentifierQuotes( $database );
  1767. }
  1768. }
  1769. $table = "{$prefix}{$table}";
  1770. if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
  1771. $table = $this->addIdentifierQuotes( "{$table}" );
  1772. }
  1773. # Merge our database and table into our final table name.
  1774. $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
  1775. return $tableName;
  1776. }
  1777. /**
  1778. * Fetch a number of table names into an array
  1779. * This is handy when you need to construct SQL for joins
  1780. *
  1781. * Example:
  1782. * extract($dbr->tableNames('user','watchlist'));
  1783. * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
  1784. * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
  1785. *
  1786. * @return array
  1787. */
  1788. public function tableNames() {
  1789. $inArray = func_get_args();
  1790. $retVal = array();
  1791. foreach ( $inArray as $name ) {
  1792. $retVal[$name] = $this->tableName( $name );
  1793. }
  1794. return $retVal;
  1795. }
  1796. /**
  1797. * Fetch a number of table names into an zero-indexed numerical array
  1798. * This is handy when you need to construct SQL for joins
  1799. *
  1800. * Example:
  1801. * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
  1802. * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
  1803. * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
  1804. *
  1805. * @return array
  1806. */
  1807. public function tableNamesN() {
  1808. $inArray = func_get_args();
  1809. $retVal = array();
  1810. foreach ( $inArray as $name ) {
  1811. $retVal[] = $this->tableName( $name );
  1812. }
  1813. return $retVal;
  1814. }
  1815. /**
  1816. * Get an aliased table name
  1817. * e.g. tableName AS newTableName
  1818. *
  1819. * @param $name string Table name, see tableName()
  1820. * @param $alias string|bool Alias (optional)
  1821. * @return string SQL name for aliased table. Will not alias a table to its own name
  1822. */
  1823. public function tableNameWithAlias( $name, $alias = false ) {
  1824. if ( !$alias || $alias == $name ) {
  1825. return $this->tableName( $name );
  1826. } else {
  1827. return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
  1828. }
  1829. }
  1830. /**
  1831. * Gets an array of aliased table names
  1832. *
  1833. * @param $tables array( [alias] => table )
  1834. * @return array of strings, see tableNameWithAlias()
  1835. */
  1836. public function tableNamesWithAlias( $tables ) {
  1837. $retval = array();
  1838. foreach ( $tables as $alias => $table ) {
  1839. if ( is_numeric( $alias ) ) {
  1840. $alias = $table;
  1841. }
  1842. $retval[] = $this->tableNameWithAlias( $table, $alias );
  1843. }
  1844. return $retval;
  1845. }
  1846. /**
  1847. * Get the aliased table name clause for a FROM clause
  1848. * which might have a JOIN and/or USE INDEX clause
  1849. *
  1850. * @param $tables array ( [alias] => table )
  1851. * @param $use_index array Same as for select()
  1852. * @param $join_conds array Same as for select()
  1853. * @return string
  1854. */
  1855. protected function tableNamesWithUseIndexOrJOIN(
  1856. $tables, $use_index = array(), $join_conds = array()
  1857. ) {
  1858. $ret = array();
  1859. $retJOIN = array();
  1860. $use_index = (array)$use_index;
  1861. $join_conds = (array)$join_conds;
  1862. foreach ( $tables as $alias => $table ) {
  1863. if ( !is_string( $alias ) ) {
  1864. // No alias? Set it equal to the table name
  1865. $alias = $table;
  1866. }
  1867. // Is there a JOIN clause for this table?
  1868. if ( isset( $join_conds[$alias] ) ) {
  1869. list( $joinType, $conds ) = $join_conds[$alias];
  1870. $tableClause = $joinType;
  1871. $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
  1872. if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
  1873. $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
  1874. if ( $use != '' ) {
  1875. $tableClause .= ' ' . $use;
  1876. }
  1877. }
  1878. $on = $this->makeList( (array)$conds, LIST_AND );
  1879. if ( $on != '' ) {
  1880. $tableClause .= ' ON (' . $on . ')';
  1881. }
  1882. $retJOIN[] = $tableClause;
  1883. // Is there an INDEX clause for this table?
  1884. } elseif ( isset( $use_index[$alias] ) ) {
  1885. $tableClause = $this->tableNameWithAlias( $table, $alias );
  1886. $tableClause .= ' ' . $this->useIndexClause(
  1887. implode( ',', (array)$use_index[$alias] ) );
  1888. $ret[] = $tableClause;
  1889. } else {
  1890. $tableClause = $this->tableNameWithAlias( $table, $alias );
  1891. $ret[] = $tableClause;
  1892. }
  1893. }
  1894. // We can't separate explicit JOIN clauses with ',', use ' ' for those
  1895. $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
  1896. $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
  1897. // Compile our final table clause
  1898. return implode( ' ', array( $straightJoins, $otherJoins ) );
  1899. }
  1900. /**
  1901. * Get the name of an index in a given table
  1902. *
  1903. * @param $index
  1904. *
  1905. * @return string
  1906. */
  1907. function indexName( $index ) {
  1908. // Backwards-compatibility hack
  1909. $renamed = array(
  1910. 'ar_usertext_timestamp' => 'usertext_timestamp',
  1911. 'un_user_id' => 'user_id',
  1912. 'un_user_ip' => 'user_ip',
  1913. );
  1914. if ( isset( $renamed[$index] ) ) {
  1915. return $renamed[$index];
  1916. } else {
  1917. return $index;
  1918. }
  1919. }
  1920. /**
  1921. * If it's a string, adds quotes and backslashes
  1922. * Otherwise returns as-is
  1923. *
  1924. * @param $s string
  1925. *
  1926. * @return string
  1927. */
  1928. function addQuotes( $s ) {
  1929. if ( $s === null ) {
  1930. return 'NULL';
  1931. } else {
  1932. # This will also quote numeric values. This should be harmless,
  1933. # and protects against weird problems that occur when they really
  1934. # _are_ strings such as article titles and string->number->string
  1935. # conversion is not 1:1.
  1936. return "'" . $this->strencode( $s ) . "'";
  1937. }
  1938. }
  1939. /**
  1940. * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
  1941. * MySQL uses `backticks` while basically everything else uses double quotes.
  1942. * Since MySQL is the odd one out here the double quotes are our generic
  1943. * and we implement backticks in DatabaseMysql.
  1944. *
  1945. * @param $s string
  1946. *
  1947. * @return string
  1948. */
  1949. public function addIdentifierQuotes( $s ) {
  1950. return '"' . str_replace( '"', '""', $s ) . '"';
  1951. }
  1952. /**
  1953. * Returns if the given identifier looks quoted or not according to
  1954. * the database convention for quoting identifiers .
  1955. *
  1956. * @param $name string
  1957. *
  1958. * @return boolean
  1959. */
  1960. public function isQuotedIdentifier( $name ) {
  1961. return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
  1962. }
  1963. /**
  1964. * Backwards compatibility, identifier quoting originated in DatabasePostgres
  1965. * which used quote_ident which does not follow our naming conventions
  1966. * was renamed to addIdentifierQuotes.
  1967. * @deprecated since 1.18 use addIdentifierQuotes
  1968. *
  1969. * @param $s string
  1970. *
  1971. * @return string
  1972. */
  1973. function quote_ident( $s ) {
  1974. wfDeprecated( __METHOD__, '1.18' );
  1975. return $this->addIdentifierQuotes( $s );
  1976. }
  1977. /**
  1978. * Escape string for safe LIKE usage.
  1979. * WARNING: you should almost never use this function directly,
  1980. * instead use buildLike() that escapes everything automatically
  1981. * @deprecated since 1.17, warnings in 1.17, removed in ???
  1982. *
  1983. * @param $s string
  1984. *
  1985. * @return string
  1986. */
  1987. public function escapeLike( $s ) {
  1988. wfDeprecated( __METHOD__, '1.17' );
  1989. return $this->escapeLikeInternal( $s );
  1990. }
  1991. /**
  1992. * @param $s string
  1993. * @return string
  1994. */
  1995. protected function escapeLikeInternal( $s ) {
  1996. $s = str_replace( '\\', '\\\\', $s );
  1997. $s = $this->strencode( $s );
  1998. $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
  1999. return $s;
  2000. }
  2001. /**
  2002. * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
  2003. * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
  2004. * Alternatively, the function could be provided with an array of aforementioned parameters.
  2005. *
  2006. * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
  2007. * for subpages of 'My page title'.
  2008. * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
  2009. *
  2010. * @since 1.16
  2011. * @return String: fully built LIKE statement
  2012. */
  2013. function buildLike() {
  2014. $params = func_get_args();
  2015. if ( count( $params ) > 0 && is_array( $params[0] ) ) {
  2016. $params = $params[0];
  2017. }
  2018. $s = '';
  2019. foreach ( $params as $value ) {
  2020. if ( $value instanceof LikeMatch ) {
  2021. $s .= $value->toString();
  2022. } else {
  2023. $s .= $this->escapeLikeInternal( $value );
  2024. }
  2025. }
  2026. return " LIKE '" . $s . "' ";
  2027. }
  2028. /**
  2029. * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
  2030. *
  2031. * @return LikeMatch
  2032. */
  2033. function anyChar() {
  2034. return new LikeMatch( '_' );
  2035. }
  2036. /**
  2037. * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
  2038. *
  2039. * @return LikeMatch
  2040. */
  2041. function anyString() {
  2042. return new LikeMatch( '%' );
  2043. }
  2044. /**
  2045. * Returns an appropriately quoted sequence value for inserting a new row.
  2046. * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
  2047. * subclass will return an integer, and save the value for insertId()
  2048. *
  2049. * Any implementation of this function should *not* involve reusing
  2050. * sequence numbers created for rolled-back transactions.
  2051. * See http://bugs.mysql.com/bug.php?id=30767 for details.
  2052. * @param $seqName string
  2053. * @return null
  2054. */
  2055. function nextSequenceValue( $seqName ) {
  2056. return null;
  2057. }
  2058. /**
  2059. * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
  2060. * is only needed because a) MySQL must be as efficient as possible due to
  2061. * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
  2062. * which index to pick. Anyway, other databases might have different
  2063. * indexes on a given table. So don't bother overriding this unless you're
  2064. * MySQL.
  2065. * @param $index
  2066. * @return string
  2067. */
  2068. function useIndexClause( $index ) {
  2069. return '';
  2070. }
  2071. /**
  2072. * REPLACE query wrapper.
  2073. *
  2074. * REPLACE is a very handy MySQL extension, which functions like an INSERT
  2075. * except that when there is a duplicate key error, the old row is deleted
  2076. * and the new row is inserted in its place.
  2077. *
  2078. * We simulate this with standard SQL with a DELETE followed by INSERT. To
  2079. * perform the delete, we need to know what the unique indexes are so that
  2080. * we know how to find the conflicting rows.
  2081. *
  2082. * It may be more efficient to leave off unique indexes which are unlikely
  2083. * to collide. However if you do this, you run the risk of encountering
  2084. * errors which wouldn't have occurred in MySQL.
  2085. *
  2086. * @param $table String: The table to replace the row(s) in.
  2087. * @param $rows array Can be either a single row to insert, or multiple rows,
  2088. * in the same format as for DatabaseBase::insert()
  2089. * @param $uniqueIndexes array is an array of indexes. Each element may be either
  2090. * a field name or an array of field names
  2091. * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
  2092. */
  2093. function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
  2094. $quotedTable = $this->tableName( $table );
  2095. if ( count( $rows ) == 0 ) {
  2096. return;
  2097. }
  2098. # Single row case
  2099. if ( !is_array( reset( $rows ) ) ) {
  2100. $rows = array( $rows );
  2101. }
  2102. foreach( $rows as $row ) {
  2103. # Delete rows which collide
  2104. if ( $uniqueIndexes ) {
  2105. $sql = "DELETE FROM $quotedTable WHERE ";
  2106. $first = true;
  2107. foreach ( $uniqueIndexes as $index ) {
  2108. if ( $first ) {
  2109. $first = false;
  2110. $sql .= '( ';
  2111. } else {
  2112. $sql .= ' ) OR ( ';
  2113. }
  2114. if ( is_array( $index ) ) {
  2115. $first2 = true;
  2116. foreach ( $index as $col ) {
  2117. if ( $first2 ) {
  2118. $first2 = false;
  2119. } else {
  2120. $sql .= ' AND ';
  2121. }
  2122. $sql .= $col . '=' . $this->addQuotes( $row[$col] );
  2123. }
  2124. } else {
  2125. $sql .= $index . '=' . $this->addQuotes( $row[$index] );
  2126. }
  2127. }
  2128. $sql .= ' )';
  2129. $this->query( $sql, $fname );
  2130. }
  2131. # Now insert the row
  2132. $this->insert( $table, $row );
  2133. }
  2134. }
  2135. /**
  2136. * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
  2137. * statement.
  2138. *
  2139. * @param $table string Table name
  2140. * @param $rows array Rows to insert
  2141. * @param $fname string Caller function name
  2142. *
  2143. * @return ResultWrapper
  2144. */
  2145. protected function nativeReplace( $table, $rows, $fname ) {
  2146. $table = $this->tableName( $table );
  2147. # Single row case
  2148. if ( !is_array( reset( $rows ) ) ) {
  2149. $rows = array( $rows );
  2150. }
  2151. $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
  2152. $first = true;
  2153. foreach ( $rows as $row ) {
  2154. if ( $first ) {
  2155. $first = false;
  2156. } else {
  2157. $sql .= ',';
  2158. }
  2159. $sql .= '(' . $this->makeList( $row ) . ')';
  2160. }
  2161. return $this->query( $sql, $fname );
  2162. }
  2163. /**
  2164. * DELETE where the condition is a join.
  2165. *
  2166. * MySQL overrides this to use a multi-table DELETE syntax, in other databases
  2167. * we use sub-selects
  2168. *
  2169. * For safety, an empty $conds will not delete everything. If you want to
  2170. * delete all rows where the join condition matches, set $conds='*'.
  2171. *
  2172. * DO NOT put the join condition in $conds.
  2173. *
  2174. * @param $delTable String: The table to delete from.
  2175. * @param $joinTable String: The other table.
  2176. * @param $delVar String: The variable to join on, in the first table.
  2177. * @param $joinVar String: The variable to join on, in the second table.
  2178. * @param $conds Array: Condition array of field names mapped to variables,
  2179. * ANDed together in the WHERE clause
  2180. * @param $fname String: Calling function name (use __METHOD__) for
  2181. * logs/profiling
  2182. */
  2183. function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
  2184. $fname = 'DatabaseBase::deleteJoin' )
  2185. {
  2186. if ( !$conds ) {
  2187. throw new DBUnexpectedError( $this,
  2188. 'DatabaseBase::deleteJoin() called with empty $conds' );
  2189. }
  2190. $delTable = $this->tableName( $delTable );
  2191. $joinTable = $this->tableName( $joinTable );
  2192. $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
  2193. if ( $conds != '*' ) {
  2194. $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
  2195. }
  2196. $sql .= ')';
  2197. $this->query( $sql, $fname );
  2198. }
  2199. /**
  2200. * Returns the size of a text field, or -1 for "unlimited"
  2201. *
  2202. * @param $table string
  2203. * @param $field string
  2204. *
  2205. * @return int
  2206. */
  2207. function textFieldSize( $table, $field ) {
  2208. $table = $this->tableName( $table );
  2209. $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
  2210. $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
  2211. $row = $this->fetchObject( $res );
  2212. $m = array();
  2213. if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
  2214. $size = $m[1];
  2215. } else {
  2216. $size = -1;
  2217. }
  2218. return $size;
  2219. }
  2220. /**
  2221. * A string to insert into queries to show that they're low-priority, like
  2222. * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
  2223. * string and nothing bad should happen.
  2224. *
  2225. * @return string Returns the text of the low priority option if it is
  2226. * supported, or a blank string otherwise
  2227. */
  2228. function lowPriorityOption() {
  2229. return '';
  2230. }
  2231. /**
  2232. * DELETE query wrapper.
  2233. *
  2234. * @param $table Array Table name
  2235. * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
  2236. * the format. Use $conds == "*" to delete all rows
  2237. * @param $fname String name of the calling function
  2238. *
  2239. * @return bool
  2240. */
  2241. function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
  2242. if ( !$conds ) {
  2243. throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
  2244. }
  2245. $table = $this->tableName( $table );
  2246. $sql = "DELETE FROM $table";
  2247. if ( $conds != '*' ) {
  2248. $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
  2249. }
  2250. return $this->query( $sql, $fname );
  2251. }
  2252. /**
  2253. * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
  2254. * into another table.
  2255. *
  2256. * @param $destTable string The table name to insert into
  2257. * @param $srcTable string|array May be either a table name, or an array of table names
  2258. * to include in a join.
  2259. *
  2260. * @param $varMap array must be an associative array of the form
  2261. * array( 'dest1' => 'source1', ...). Source items may be literals
  2262. * rather than field names, but strings should be quoted with
  2263. * DatabaseBase::addQuotes()
  2264. *
  2265. * @param $conds array Condition array. See $conds in DatabaseBase::select() for
  2266. * the details of the format of condition arrays. May be "*" to copy the
  2267. * whole table.
  2268. *
  2269. * @param $fname string The function name of the caller, from __METHOD__
  2270. *
  2271. * @param $insertOptions array Options for the INSERT part of the query, see
  2272. * DatabaseBase::insert() for details.
  2273. * @param $selectOptions array Options for the SELECT part of the query, see
  2274. * DatabaseBase::select() for details.
  2275. *
  2276. * @return ResultWrapper
  2277. */
  2278. function insertSelect( $destTable, $srcTable, $varMap, $conds,
  2279. $fname = 'DatabaseBase::insertSelect',
  2280. $insertOptions = array(), $selectOptions = array() )
  2281. {
  2282. $destTable = $this->tableName( $destTable );
  2283. if ( is_array( $insertOptions ) ) {
  2284. $insertOptions = implode( ' ', $insertOptions );
  2285. }
  2286. if ( !is_array( $selectOptions ) ) {
  2287. $selectOptions = array( $selectOptions );
  2288. }
  2289. list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
  2290. if ( is_array( $srcTable ) ) {
  2291. $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
  2292. } else {
  2293. $srcTable = $this->tableName( $srcTable );
  2294. }
  2295. $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
  2296. " SELECT $startOpts " . implode( ',', $varMap ) .
  2297. " FROM $srcTable $useIndex ";
  2298. if ( $conds != '*' ) {
  2299. if ( is_array( $conds ) ) {
  2300. $conds = $this->makeList( $conds, LIST_AND );
  2301. }
  2302. $sql .= " WHERE $conds";
  2303. }
  2304. $sql .= " $tailOpts";
  2305. return $this->query( $sql, $fname );
  2306. }
  2307. /**
  2308. * Construct a LIMIT query with optional offset. This is used for query
  2309. * pages. The SQL should be adjusted so that only the first $limit rows
  2310. * are returned. If $offset is provided as well, then the first $offset
  2311. * rows should be discarded, and the next $limit rows should be returned.
  2312. * If the result of the query is not ordered, then the rows to be returned
  2313. * are theoretically arbitrary.
  2314. *
  2315. * $sql is expected to be a SELECT, if that makes a difference. For
  2316. * UPDATE, limitResultForUpdate should be used.
  2317. *
  2318. * The version provided by default works in MySQL and SQLite. It will very
  2319. * likely need to be overridden for most other DBMSes.
  2320. *
  2321. * @param $sql String SQL query we will append the limit too
  2322. * @param $limit Integer the SQL limit
  2323. * @param $offset Integer|false the SQL offset (default false)
  2324. *
  2325. * @return string
  2326. */
  2327. function limitResult( $sql, $limit, $offset = false ) {
  2328. if ( !is_numeric( $limit ) ) {
  2329. throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
  2330. }
  2331. return "$sql LIMIT "
  2332. . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
  2333. . "{$limit} ";
  2334. }
  2335. /**
  2336. * @param $sql
  2337. * @param $num
  2338. * @return string
  2339. */
  2340. function limitResultForUpdate( $sql, $num ) {
  2341. return $this->limitResult( $sql, $num, 0 );
  2342. }
  2343. /**
  2344. * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
  2345. * within the UNION construct.
  2346. * @return Boolean
  2347. */
  2348. function unionSupportsOrderAndLimit() {
  2349. return true; // True for almost every DB supported
  2350. }
  2351. /**
  2352. * Construct a UNION query
  2353. * This is used for providing overload point for other DB abstractions
  2354. * not compatible with the MySQL syntax.
  2355. * @param $sqls Array: SQL statements to combine
  2356. * @param $all Boolean: use UNION ALL
  2357. * @return String: SQL fragment
  2358. */
  2359. function unionQueries( $sqls, $all ) {
  2360. $glue = $all ? ') UNION ALL (' : ') UNION (';
  2361. return '(' . implode( $glue, $sqls ) . ')';
  2362. }
  2363. /**
  2364. * Returns an SQL expression for a simple conditional. This doesn't need
  2365. * to be overridden unless CASE isn't supported in your DBMS.
  2366. *
  2367. * @param $cond String: SQL expression which will result in a boolean value
  2368. * @param $trueVal String: SQL expression to return if true
  2369. * @param $falseVal String: SQL expression to return if false
  2370. * @return String: SQL fragment
  2371. */
  2372. function conditional( $cond, $trueVal, $falseVal ) {
  2373. return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
  2374. }
  2375. /**
  2376. * Returns a comand for str_replace function in SQL query.
  2377. * Uses REPLACE() in MySQL
  2378. *
  2379. * @param $orig String: column to modify
  2380. * @param $old String: column to seek
  2381. * @param $new String: column to replace with
  2382. *
  2383. * @return string
  2384. */
  2385. function strreplace( $orig, $old, $new ) {
  2386. return "REPLACE({$orig}, {$old}, {$new})";
  2387. }
  2388. /**
  2389. * Determines how long the server has been up
  2390. * STUB
  2391. *
  2392. * @return int
  2393. */
  2394. function getServerUptime() {
  2395. return 0;
  2396. }
  2397. /**
  2398. * Determines if the last failure was due to a deadlock
  2399. * STUB
  2400. *
  2401. * @return bool
  2402. */
  2403. function wasDeadlock() {
  2404. return false;
  2405. }
  2406. /**
  2407. * Determines if the last failure was due to a lock timeout
  2408. * STUB
  2409. *
  2410. * @return bool
  2411. */
  2412. function wasLockTimeout() {
  2413. return false;
  2414. }
  2415. /**
  2416. * Determines if the last query error was something that should be dealt
  2417. * with by pinging the connection and reissuing the query.
  2418. * STUB
  2419. *
  2420. * @return bool
  2421. */
  2422. function wasErrorReissuable() {
  2423. return false;
  2424. }
  2425. /**
  2426. * Determines if the last failure was due to the database being read-only.
  2427. * STUB
  2428. *
  2429. * @return bool
  2430. */
  2431. function wasReadOnlyError() {
  2432. return false;
  2433. }
  2434. /**
  2435. * Perform a deadlock-prone transaction.
  2436. *
  2437. * This function invokes a callback function to perform a set of write
  2438. * queries. If a deadlock occurs during the processing, the transaction
  2439. * will be rolled back and the callback function will be called again.
  2440. *
  2441. * Usage:
  2442. * $dbw->deadlockLoop( callback, ... );
  2443. *
  2444. * Extra arguments are passed through to the specified callback function.
  2445. *
  2446. * Returns whatever the callback function returned on its successful,
  2447. * iteration, or false on error, for example if the retry limit was
  2448. * reached.
  2449. *
  2450. * @return bool
  2451. */
  2452. function deadlockLoop() {
  2453. $this->begin( __METHOD__ );
  2454. $args = func_get_args();
  2455. $function = array_shift( $args );
  2456. $oldIgnore = $this->ignoreErrors( true );
  2457. $tries = DEADLOCK_TRIES;
  2458. if ( is_array( $function ) ) {
  2459. $fname = $function[0];
  2460. } else {
  2461. $fname = $function;
  2462. }
  2463. do {
  2464. $retVal = call_user_func_array( $function, $args );
  2465. $error = $this->lastError();
  2466. $errno = $this->lastErrno();
  2467. $sql = $this->lastQuery();
  2468. if ( $errno ) {
  2469. if ( $this->wasDeadlock() ) {
  2470. # Retry
  2471. usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
  2472. } else {
  2473. $this->reportQueryError( $error, $errno, $sql, $fname );
  2474. }
  2475. }
  2476. } while ( $this->wasDeadlock() && --$tries > 0 );
  2477. $this->ignoreErrors( $oldIgnore );
  2478. if ( $tries <= 0 ) {
  2479. $this->rollback( __METHOD__ );
  2480. $this->reportQueryError( $error, $errno, $sql, $fname );
  2481. return false;
  2482. } else {
  2483. $this->commit( __METHOD__ );
  2484. return $retVal;
  2485. }
  2486. }
  2487. /**
  2488. * Wait for the slave to catch up to a given master position.
  2489. *
  2490. * @param $pos DBMasterPos object
  2491. * @param $timeout Integer: the maximum number of seconds to wait for
  2492. * synchronisation
  2493. *
  2494. * @return An integer: zero if the slave was past that position already,
  2495. * greater than zero if we waited for some period of time, less than
  2496. * zero if we timed out.
  2497. */
  2498. function masterPosWait( DBMasterPos $pos, $timeout ) {
  2499. wfProfileIn( __METHOD__ );
  2500. if ( !is_null( $this->mFakeSlaveLag ) ) {
  2501. $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
  2502. if ( $wait > $timeout * 1e6 ) {
  2503. wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
  2504. wfProfileOut( __METHOD__ );
  2505. return -1;
  2506. } elseif ( $wait > 0 ) {
  2507. wfDebug( "Fake slave waiting $wait us\n" );
  2508. usleep( $wait );
  2509. wfProfileOut( __METHOD__ );
  2510. return 1;
  2511. } else {
  2512. wfDebug( "Fake slave up to date ($wait us)\n" );
  2513. wfProfileOut( __METHOD__ );
  2514. return 0;
  2515. }
  2516. }
  2517. wfProfileOut( __METHOD__ );
  2518. # Real waits are implemented in the subclass.
  2519. return 0;
  2520. }
  2521. /**
  2522. * Get the replication position of this slave
  2523. *
  2524. * @return DBMasterPos, or false if this is not a slave.
  2525. */
  2526. function getSlavePos() {
  2527. if ( !is_null( $this->mFakeSlaveLag ) ) {
  2528. $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
  2529. wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
  2530. return $pos;
  2531. } else {
  2532. # Stub
  2533. return false;
  2534. }
  2535. }
  2536. /**
  2537. * Get the position of this master
  2538. *
  2539. * @return DBMasterPos, or false if this is not a master
  2540. */
  2541. function getMasterPos() {
  2542. if ( $this->mFakeMaster ) {
  2543. return new MySQLMasterPos( 'fake', microtime( true ) );
  2544. } else {
  2545. return false;
  2546. }
  2547. }
  2548. /**
  2549. * Begin a transaction, committing any previously open transaction
  2550. *
  2551. * @param $fname string
  2552. */
  2553. function begin( $fname = 'DatabaseBase::begin' ) {
  2554. $this->query( 'BEGIN', $fname );
  2555. $this->mTrxLevel = 1;
  2556. }
  2557. /**
  2558. * End a transaction
  2559. *
  2560. * @param $fname string
  2561. */
  2562. function commit( $fname = 'DatabaseBase::commit' ) {
  2563. if ( $this->mTrxLevel ) {
  2564. $this->query( 'COMMIT', $fname );
  2565. $this->mTrxLevel = 0;
  2566. }
  2567. }
  2568. /**
  2569. * Rollback a transaction.
  2570. * No-op on non-transactional databases.
  2571. *
  2572. * @param $fname string
  2573. */
  2574. function rollback( $fname = 'DatabaseBase::rollback' ) {
  2575. if ( $this->mTrxLevel ) {
  2576. $this->query( 'ROLLBACK', $fname, true );
  2577. $this->mTrxLevel = 0;
  2578. }
  2579. }
  2580. /**
  2581. * Creates a new table with structure copied from existing table
  2582. * Note that unlike most database abstraction functions, this function does not
  2583. * automatically append database prefix, because it works at a lower
  2584. * abstraction level.
  2585. * The table names passed to this function shall not be quoted (this
  2586. * function calls addIdentifierQuotes when needed).
  2587. *
  2588. * @param $oldName String: name of table whose structure should be copied
  2589. * @param $newName String: name of table to be created
  2590. * @param $temporary Boolean: whether the new table should be temporary
  2591. * @param $fname String: calling function name
  2592. * @return Boolean: true if operation was successful
  2593. */
  2594. function duplicateTableStructure( $oldName, $newName, $temporary = false,
  2595. $fname = 'DatabaseBase::duplicateTableStructure' )
  2596. {
  2597. throw new MWException(
  2598. 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
  2599. }
  2600. /**
  2601. * List all tables on the database
  2602. *
  2603. * @param $prefix Only show tables with this prefix, e.g. mw_
  2604. * @param $fname String: calling function name
  2605. */
  2606. function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
  2607. throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
  2608. }
  2609. /**
  2610. * Convert a timestamp in one of the formats accepted by wfTimestamp()
  2611. * to the format used for inserting into timestamp fields in this DBMS.
  2612. *
  2613. * The result is unquoted, and needs to be passed through addQuotes()
  2614. * before it can be included in raw SQL.
  2615. *
  2616. * @param $ts string|int
  2617. *
  2618. * @return string
  2619. */
  2620. function timestamp( $ts = 0 ) {
  2621. return wfTimestamp( TS_MW, $ts );
  2622. }
  2623. /**
  2624. * Convert a timestamp in one of the formats accepted by wfTimestamp()
  2625. * to the format used for inserting into timestamp fields in this DBMS. If
  2626. * NULL is input, it is passed through, allowing NULL values to be inserted
  2627. * into timestamp fields.
  2628. *
  2629. * The result is unquoted, and needs to be passed through addQuotes()
  2630. * before it can be included in raw SQL.
  2631. *
  2632. * @param $ts string|int
  2633. *
  2634. * @return string
  2635. */
  2636. function timestampOrNull( $ts = null ) {
  2637. if ( is_null( $ts ) ) {
  2638. return null;
  2639. } else {
  2640. return $this->timestamp( $ts );
  2641. }
  2642. }
  2643. /**
  2644. * Take the result from a query, and wrap it in a ResultWrapper if
  2645. * necessary. Boolean values are passed through as is, to indicate success
  2646. * of write queries or failure.
  2647. *
  2648. * Once upon a time, DatabaseBase::query() returned a bare MySQL result
  2649. * resource, and it was necessary to call this function to convert it to
  2650. * a wrapper. Nowadays, raw database objects are never exposed to external
  2651. * callers, so this is unnecessary in external code. For compatibility with
  2652. * old code, ResultWrapper objects are passed through unaltered.
  2653. *
  2654. * @param $result bool|ResultWrapper
  2655. *
  2656. * @return bool|ResultWrapper
  2657. */
  2658. function resultObject( $result ) {
  2659. if ( empty( $result ) ) {
  2660. return false;
  2661. } elseif ( $result instanceof ResultWrapper ) {
  2662. return $result;
  2663. } elseif ( $result === true ) {
  2664. // Successful write query
  2665. return $result;
  2666. } else {
  2667. return new ResultWrapper( $this, $result );
  2668. }
  2669. }
  2670. /**
  2671. * Return aggregated value alias
  2672. *
  2673. * @param $valuedata
  2674. * @param $valuename string
  2675. *
  2676. * @return string
  2677. */
  2678. function aggregateValue ( $valuedata, $valuename = 'value' ) {
  2679. return $valuename;
  2680. }
  2681. /**
  2682. * Ping the server and try to reconnect if it there is no connection
  2683. *
  2684. * @return bool Success or failure
  2685. */
  2686. function ping() {
  2687. # Stub. Not essential to override.
  2688. return true;
  2689. }
  2690. /**
  2691. * Get slave lag. Currently supported only by MySQL.
  2692. *
  2693. * Note that this function will generate a fatal error on many
  2694. * installations. Most callers should use LoadBalancer::safeGetLag()
  2695. * instead.
  2696. *
  2697. * @return Database replication lag in seconds
  2698. */
  2699. function getLag() {
  2700. return intval( $this->mFakeSlaveLag );
  2701. }
  2702. /**
  2703. * Return the maximum number of items allowed in a list, or 0 for unlimited.
  2704. *
  2705. * @return int
  2706. */
  2707. function maxListLen() {
  2708. return 0;
  2709. }
  2710. /**
  2711. * Some DBMSs have a special format for inserting into blob fields, they
  2712. * don't allow simple quoted strings to be inserted. To insert into such
  2713. * a field, pass the data through this function before passing it to
  2714. * DatabaseBase::insert().
  2715. * @param $b string
  2716. * @return string
  2717. */
  2718. function encodeBlob( $b ) {
  2719. return $b;
  2720. }
  2721. /**
  2722. * Some DBMSs return a special placeholder object representing blob fields
  2723. * in result objects. Pass the object through this function to return the
  2724. * original string.
  2725. * @param $b string
  2726. * @return string
  2727. */
  2728. function decodeBlob( $b ) {
  2729. return $b;
  2730. }
  2731. /**
  2732. * Override database's default connection timeout
  2733. *
  2734. * @param $timeout Integer in seconds
  2735. * @return void
  2736. * @deprecated since 1.19; use setSessionOptions()
  2737. */
  2738. public function setTimeout( $timeout ) {
  2739. wfDeprecated( __METHOD__, '1.19' );
  2740. $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
  2741. }
  2742. /**
  2743. * Override database's default behavior. $options include:
  2744. * 'connTimeout' : Set the connection timeout value in seconds.
  2745. * May be useful for very long batch queries such as
  2746. * full-wiki dumps, where a single query reads out over
  2747. * hours or days.
  2748. *
  2749. * @param $options Array
  2750. * @return void
  2751. */
  2752. public function setSessionOptions( array $options ) {}
  2753. /**
  2754. * Read and execute SQL commands from a file.
  2755. *
  2756. * Returns true on success, error string or exception on failure (depending
  2757. * on object's error ignore settings).
  2758. *
  2759. * @param $filename String: File name to open
  2760. * @param $lineCallback Callback: Optional function called before reading each line
  2761. * @param $resultCallback Callback: Optional function called for each MySQL result
  2762. * @param $fname String: Calling function name or false if name should be
  2763. * generated dynamically using $filename
  2764. * @return bool|string
  2765. */
  2766. function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
  2767. wfSuppressWarnings();
  2768. $fp = fopen( $filename, 'r' );
  2769. wfRestoreWarnings();
  2770. if ( false === $fp ) {
  2771. throw new MWException( "Could not open \"{$filename}\".\n" );
  2772. }
  2773. if ( !$fname ) {
  2774. $fname = __METHOD__ . "( $filename )";
  2775. }
  2776. try {
  2777. $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
  2778. }
  2779. catch ( MWException $e ) {
  2780. fclose( $fp );
  2781. throw $e;
  2782. }
  2783. fclose( $fp );
  2784. return $error;
  2785. }
  2786. /**
  2787. * Get the full path of a patch file. Originally based on archive()
  2788. * from updaters.inc. Keep in mind this always returns a patch, as
  2789. * it fails back to MySQL if no DB-specific patch can be found
  2790. *
  2791. * @param $patch String The name of the patch, like patch-something.sql
  2792. * @return String Full path to patch file
  2793. */
  2794. public function patchPath( $patch ) {
  2795. global $IP;
  2796. $dbType = $this->getType();
  2797. if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
  2798. return "$IP/maintenance/$dbType/archives/$patch";
  2799. } else {
  2800. return "$IP/maintenance/archives/$patch";
  2801. }
  2802. }
  2803. /**
  2804. * Set variables to be used in sourceFile/sourceStream, in preference to the
  2805. * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
  2806. * all. If it's set to false, $GLOBALS will be used.
  2807. *
  2808. * @param $vars False, or array mapping variable name to value.
  2809. */
  2810. function setSchemaVars( $vars ) {
  2811. $this->mSchemaVars = $vars;
  2812. }
  2813. /**
  2814. * Read and execute commands from an open file handle.
  2815. *
  2816. * Returns true on success, error string or exception on failure (depending
  2817. * on object's error ignore settings).
  2818. *
  2819. * @param $fp Resource: File handle
  2820. * @param $lineCallback Callback: Optional function called before reading each line
  2821. * @param $resultCallback Callback: Optional function called for each MySQL result
  2822. * @param $fname String: Calling function name
  2823. * @param $inputCallback Callback: Optional function called for each complete line (ended with ;) sent
  2824. * @return bool|string
  2825. */
  2826. public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
  2827. $fname = 'DatabaseBase::sourceStream', $inputCallback = false )
  2828. {
  2829. $cmd = '';
  2830. while ( !feof( $fp ) ) {
  2831. if ( $lineCallback ) {
  2832. call_user_func( $lineCallback );
  2833. }
  2834. $line = trim( fgets( $fp ) );
  2835. if ( $line == '' ) {
  2836. continue;
  2837. }
  2838. if ( '-' == $line[0] && '-' == $line[1] ) {
  2839. continue;
  2840. }
  2841. if ( $cmd != '' ) {
  2842. $cmd .= ' ';
  2843. }
  2844. $done = $this->streamStatementEnd( $cmd, $line );
  2845. $cmd .= "$line\n";
  2846. if ( $done || feof( $fp ) ) {
  2847. $cmd = $this->replaceVars( $cmd );
  2848. if ( $inputCallback ) {
  2849. call_user_func( $inputCallback, $cmd );
  2850. }
  2851. $res = $this->query( $cmd, $fname );
  2852. if ( $resultCallback ) {
  2853. call_user_func( $resultCallback, $res, $this );
  2854. }
  2855. if ( false === $res ) {
  2856. $err = $this->lastError();
  2857. return "Query \"{$cmd}\" failed with error code \"$err\".\n";
  2858. }
  2859. $cmd = '';
  2860. }
  2861. }
  2862. return true;
  2863. }
  2864. /**
  2865. * Called by sourceStream() to check if we've reached a statement end
  2866. *
  2867. * @param $sql String SQL assembled so far
  2868. * @param $newLine String New line about to be added to $sql
  2869. * @return Bool Whether $newLine contains end of the statement
  2870. */
  2871. public function streamStatementEnd( &$sql, &$newLine ) {
  2872. if ( $this->delimiter ) {
  2873. $prev = $newLine;
  2874. $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
  2875. if ( $newLine != $prev ) {
  2876. return true;
  2877. }
  2878. }
  2879. return false;
  2880. }
  2881. /**
  2882. * Database independent variable replacement. Replaces a set of variables
  2883. * in an SQL statement with their contents as given by $this->getSchemaVars().
  2884. *
  2885. * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
  2886. *
  2887. * - '{$var}' should be used for text and is passed through the database's
  2888. * addQuotes method.
  2889. * - `{$var}` should be used for identifiers (eg: table and database names),
  2890. * it is passed through the database's addIdentifierQuotes method which
  2891. * can be overridden if the database uses something other than backticks.
  2892. * - / *$var* / is just encoded, besides traditional table prefix and
  2893. * table options its use should be avoided.
  2894. *
  2895. * @param $ins String: SQL statement to replace variables in
  2896. * @return String The new SQL statement with variables replaced
  2897. */
  2898. protected function replaceSchemaVars( $ins ) {
  2899. $vars = $this->getSchemaVars();
  2900. foreach ( $vars as $var => $value ) {
  2901. // replace '{$var}'
  2902. $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
  2903. // replace `{$var}`
  2904. $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
  2905. // replace /*$var*/
  2906. $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
  2907. }
  2908. return $ins;
  2909. }
  2910. /**
  2911. * Replace variables in sourced SQL
  2912. *
  2913. * @param $ins string
  2914. *
  2915. * @return string
  2916. */
  2917. protected function replaceVars( $ins ) {
  2918. $ins = $this->replaceSchemaVars( $ins );
  2919. // Table prefixes
  2920. $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
  2921. array( $this, 'tableNameCallback' ), $ins );
  2922. // Index names
  2923. $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
  2924. array( $this, 'indexNameCallback' ), $ins );
  2925. return $ins;
  2926. }
  2927. /**
  2928. * Get schema variables. If none have been set via setSchemaVars(), then
  2929. * use some defaults from the current object.
  2930. *
  2931. * @return array
  2932. */
  2933. protected function getSchemaVars() {
  2934. if ( $this->mSchemaVars ) {
  2935. return $this->mSchemaVars;
  2936. } else {
  2937. return $this->getDefaultSchemaVars();
  2938. }
  2939. }
  2940. /**
  2941. * Get schema variables to use if none have been set via setSchemaVars().
  2942. *
  2943. * Override this in derived classes to provide variables for tables.sql
  2944. * and SQL patch files.
  2945. *
  2946. * @return array
  2947. */
  2948. protected function getDefaultSchemaVars() {
  2949. return array();
  2950. }
  2951. /**
  2952. * Table name callback
  2953. *
  2954. * @param $matches array
  2955. *
  2956. * @return string
  2957. */
  2958. protected function tableNameCallback( $matches ) {
  2959. return $this->tableName( $matches[1] );
  2960. }
  2961. /**
  2962. * Index name callback
  2963. *
  2964. * @param $matches array
  2965. *
  2966. * @return string
  2967. */
  2968. protected function indexNameCallback( $matches ) {
  2969. return $this->indexName( $matches[1] );
  2970. }
  2971. /**
  2972. * Build a concatenation list to feed into a SQL query
  2973. * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
  2974. * @return String
  2975. */
  2976. function buildConcat( $stringList ) {
  2977. return 'CONCAT(' . implode( ',', $stringList ) . ')';
  2978. }
  2979. /**
  2980. * Acquire a named lock
  2981. *
  2982. * Abstracted from Filestore::lock() so child classes can implement for
  2983. * their own needs.
  2984. *
  2985. * @param $lockName String: name of lock to aquire
  2986. * @param $method String: name of method calling us
  2987. * @param $timeout Integer: timeout
  2988. * @return Boolean
  2989. */
  2990. public function lock( $lockName, $method, $timeout = 5 ) {
  2991. return true;
  2992. }
  2993. /**
  2994. * Release a lock.
  2995. *
  2996. * @param $lockName String: Name of lock to release
  2997. * @param $method String: Name of method calling us
  2998. *
  2999. * @return Returns 1 if the lock was released, 0 if the lock was not established
  3000. * by this thread (in which case the lock is not released), and NULL if the named
  3001. * lock did not exist
  3002. */
  3003. public function unlock( $lockName, $method ) {
  3004. return true;
  3005. }
  3006. /**
  3007. * Lock specific tables
  3008. *
  3009. * @param $read Array of tables to lock for read access
  3010. * @param $write Array of tables to lock for write access
  3011. * @param $method String name of caller
  3012. * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
  3013. *
  3014. * @return bool
  3015. */
  3016. public function lockTables( $read, $write, $method, $lowPriority = true ) {
  3017. return true;
  3018. }
  3019. /**
  3020. * Unlock specific tables
  3021. *
  3022. * @param $method String the caller
  3023. *
  3024. * @return bool
  3025. */
  3026. public function unlockTables( $method ) {
  3027. return true;
  3028. }
  3029. /**
  3030. * Delete a table
  3031. * @param $tableName string
  3032. * @param $fName string
  3033. * @return bool|ResultWrapper
  3034. * @since 1.18
  3035. */
  3036. public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
  3037. if( !$this->tableExists( $tableName, $fName ) ) {
  3038. return false;
  3039. }
  3040. $sql = "DROP TABLE " . $this->tableName( $tableName );
  3041. if( $this->cascadingDeletes() ) {
  3042. $sql .= " CASCADE";
  3043. }
  3044. return $this->query( $sql, $fName );
  3045. }
  3046. /**
  3047. * Get search engine class. All subclasses of this need to implement this
  3048. * if they wish to use searching.
  3049. *
  3050. * @return String
  3051. */
  3052. public function getSearchEngine() {
  3053. return 'SearchEngineDummy';
  3054. }
  3055. /**
  3056. * Find out when 'infinity' is. Most DBMSes support this. This is a special
  3057. * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
  3058. * because "i" sorts after all numbers.
  3059. *
  3060. * @return String
  3061. */
  3062. public function getInfinity() {
  3063. return 'infinity';
  3064. }
  3065. /**
  3066. * Encode an expiry time
  3067. *
  3068. * @param $expiry String: timestamp for expiry, or the 'infinity' string
  3069. * @return String
  3070. */
  3071. public function encodeExpiry( $expiry ) {
  3072. if ( $expiry == '' || $expiry == $this->getInfinity() ) {
  3073. return $this->getInfinity();
  3074. } else {
  3075. return $this->timestamp( $expiry );
  3076. }
  3077. }
  3078. /**
  3079. * Allow or deny "big selects" for this session only. This is done by setting
  3080. * the sql_big_selects session variable.
  3081. *
  3082. * This is a MySQL-specific feature.
  3083. *
  3084. * @param $value Mixed: true for allow, false for deny, or "default" to
  3085. * restore the initial value
  3086. */
  3087. public function setBigSelects( $value = true ) {
  3088. // no-op
  3089. }
  3090. }