PageRenderTime 58ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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…

Large files files are truncated, but you can click here to view the full file