DatabaseMysqlBase.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. <?php
  2. /**
  3. * This is the MySQL database abstraction layer.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup Database
  22. */
  23. namespace Wikimedia\Rdbms;
  24. use DateTime;
  25. use DateTimeZone;
  26. use Wikimedia\AtEase\AtEase;
  27. use InvalidArgumentException;
  28. use Exception;
  29. use RuntimeException;
  30. use stdClass;
  31. /**
  32. * Database abstraction object for MySQL.
  33. * Defines methods independent on used MySQL extension.
  34. *
  35. * @ingroup Database
  36. * @since 1.22
  37. * @see Database
  38. */
  39. abstract class DatabaseMysqlBase extends Database {
  40. /** @var MysqlMasterPos */
  41. protected $lastKnownReplicaPos;
  42. /** @var string Method to detect replica DB lag */
  43. protected $lagDetectionMethod;
  44. /** @var array Method to detect replica DB lag */
  45. protected $lagDetectionOptions = [];
  46. /** @var bool bool Whether to use GTID methods */
  47. protected $useGTIDs = false;
  48. /** @var string|null */
  49. protected $sslKeyPath;
  50. /** @var string|null */
  51. protected $sslCertPath;
  52. /** @var string|null */
  53. protected $sslCAFile;
  54. /** @var string|null */
  55. protected $sslCAPath;
  56. /** @var string[]|null */
  57. protected $sslCiphers;
  58. /** @var string sql_mode value to send on connection */
  59. protected $sqlMode;
  60. /** @var bool Use experimental UTF-8 transmission encoding */
  61. protected $utf8Mode;
  62. /** @var bool|null */
  63. protected $defaultBigSelects = null;
  64. /** @var bool|null */
  65. private $insertSelectIsSafe = null;
  66. /** @var stdClass|null */
  67. private $replicationInfoRow = null;
  68. // Cache getServerId() for 24 hours
  69. const SERVER_ID_CACHE_TTL = 86400;
  70. /** @var float Warn if lag estimates are made for transactions older than this many seconds */
  71. const LAG_STALE_WARN_THRESHOLD = 0.100;
  72. /**
  73. * Additional $params include:
  74. * - lagDetectionMethod : set to one of (Seconds_Behind_Master,pt-heartbeat).
  75. * pt-heartbeat assumes the table is at heartbeat.heartbeat
  76. * and uses UTC timestamps in the heartbeat.ts column.
  77. * (https://www.percona.com/doc/percona-toolkit/2.2/pt-heartbeat.html)
  78. * - lagDetectionOptions : if using pt-heartbeat, this can be set to an array map to change
  79. * the default behavior. Normally, the heartbeat row with the server
  80. * ID of this server's master will be used. Set the "conds" field to
  81. * override the query conditions, e.g. ['shard' => 's1'].
  82. * - useGTIDs : use GTID methods like MASTER_GTID_WAIT() when possible.
  83. * - insertSelectIsSafe : force that native INSERT SELECT is or is not safe [default: null]
  84. * - sslKeyPath : path to key file [default: null]
  85. * - sslCertPath : path to certificate file [default: null]
  86. * - sslCAFile: path to a single certificate authority PEM file [default: null]
  87. * - sslCAPath : parth to certificate authority PEM directory [default: null]
  88. * - sslCiphers : array list of allowable ciphers [default: null]
  89. * @param array $params
  90. */
  91. public function __construct( array $params ) {
  92. $this->lagDetectionMethod = $params['lagDetectionMethod'] ?? 'Seconds_Behind_Master';
  93. $this->lagDetectionOptions = $params['lagDetectionOptions'] ?? [];
  94. $this->useGTIDs = !empty( $params['useGTIDs' ] );
  95. foreach ( [ 'KeyPath', 'CertPath', 'CAFile', 'CAPath', 'Ciphers' ] as $name ) {
  96. $var = "ssl{$name}";
  97. if ( isset( $params[$var] ) ) {
  98. $this->$var = $params[$var];
  99. }
  100. }
  101. $this->sqlMode = $params['sqlMode'] ?? null;
  102. $this->utf8Mode = !empty( $params['utf8Mode'] );
  103. $this->insertSelectIsSafe = isset( $params['insertSelectIsSafe'] )
  104. ? (bool)$params['insertSelectIsSafe'] : null;
  105. parent::__construct( $params );
  106. }
  107. /**
  108. * @return string
  109. */
  110. public function getType() {
  111. return 'mysql';
  112. }
  113. protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
  114. $this->close();
  115. if ( $schema !== null ) {
  116. throw $this->newExceptionAfterConnectError( "Got schema '$schema'; not supported." );
  117. }
  118. $this->server = $server;
  119. $this->user = $user;
  120. $this->password = $password;
  121. $this->installErrorHandler();
  122. try {
  123. $this->conn = $this->mysqlConnect( $this->server, $dbName );
  124. } catch ( Exception $e ) {
  125. $this->restoreErrorHandler();
  126. throw $this->newExceptionAfterConnectError( $e->getMessage() );
  127. }
  128. $error = $this->restoreErrorHandler();
  129. if ( !$this->conn ) {
  130. throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
  131. }
  132. try {
  133. $this->currentDomain = new DatabaseDomain(
  134. strlen( $dbName ) ? $dbName : null,
  135. null,
  136. $tablePrefix
  137. );
  138. // Abstract over any insane MySQL defaults
  139. $set = [ 'group_concat_max_len = 262144' ];
  140. // Set SQL mode, default is turning them all off, can be overridden or skipped with null
  141. if ( is_string( $this->sqlMode ) ) {
  142. $set[] = 'sql_mode = ' . $this->addQuotes( $this->sqlMode );
  143. }
  144. // Set any custom settings defined by site config
  145. // (e.g. https://dev.mysql.com/doc/refman/4.1/en/innodb-parameters.html)
  146. foreach ( $this->connectionVariables as $var => $val ) {
  147. // Escape strings but not numbers to avoid MySQL complaining
  148. if ( !is_int( $val ) && !is_float( $val ) ) {
  149. $val = $this->addQuotes( $val );
  150. }
  151. $set[] = $this->addIdentifierQuotes( $var ) . ' = ' . $val;
  152. }
  153. if ( $set ) {
  154. $this->query(
  155. 'SET ' . implode( ', ', $set ),
  156. __METHOD__,
  157. self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY
  158. );
  159. }
  160. } catch ( Exception $e ) {
  161. throw $this->newExceptionAfterConnectError( $e->getMessage() );
  162. }
  163. }
  164. protected function doSelectDomain( DatabaseDomain $domain ) {
  165. if ( $domain->getSchema() !== null ) {
  166. throw new DBExpectedError(
  167. $this,
  168. __CLASS__ . ": domain '{$domain->getId()}' has a schema component"
  169. );
  170. }
  171. $database = $domain->getDatabase();
  172. // A null database means "don't care" so leave it as is and update the table prefix
  173. if ( $database === null ) {
  174. $this->currentDomain = new DatabaseDomain(
  175. $this->currentDomain->getDatabase(),
  176. null,
  177. $domain->getTablePrefix()
  178. );
  179. return true;
  180. }
  181. if ( $database !== $this->getDBname() ) {
  182. $sql = 'USE ' . $this->addIdentifierQuotes( $database );
  183. list( $res, $err, $errno ) =
  184. $this->executeQuery( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
  185. if ( $res === false ) {
  186. $this->reportQueryError( $err, $errno, $sql, __METHOD__ );
  187. return false; // unreachable
  188. }
  189. }
  190. // Update that domain fields on success (no exception thrown)
  191. $this->currentDomain = $domain;
  192. return true;
  193. }
  194. /**
  195. * Open a connection to a MySQL server
  196. *
  197. * @param string $realServer
  198. * @param string|null $dbName
  199. * @return mixed|null Driver connection handle
  200. * @throws DBConnectionError
  201. */
  202. abstract protected function mysqlConnect( $realServer, $dbName );
  203. /**
  204. * @param IResultWrapper|resource $res
  205. * @throws DBUnexpectedError
  206. */
  207. public function freeResult( $res ) {
  208. AtEase::suppressWarnings();
  209. $ok = $this->mysqlFreeResult( ResultWrapper::unwrap( $res ) );
  210. AtEase::restoreWarnings();
  211. if ( !$ok ) {
  212. throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
  213. }
  214. }
  215. /**
  216. * Free result memory
  217. *
  218. * @param resource $res Raw result
  219. * @return bool
  220. */
  221. abstract protected function mysqlFreeResult( $res );
  222. /**
  223. * @param IResultWrapper|resource $res
  224. * @return stdClass|bool
  225. * @throws DBUnexpectedError
  226. */
  227. public function fetchObject( $res ) {
  228. AtEase::suppressWarnings();
  229. $row = $this->mysqlFetchObject( ResultWrapper::unwrap( $res ) );
  230. AtEase::restoreWarnings();
  231. $errno = $this->lastErrno();
  232. // Unfortunately, mysql_fetch_object does not reset the last errno.
  233. // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
  234. // these are the only errors mysql_fetch_object can cause.
  235. // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
  236. if ( $errno == 2000 || $errno == 2013 ) {
  237. throw new DBUnexpectedError(
  238. $this,
  239. 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
  240. );
  241. }
  242. return $row;
  243. }
  244. /**
  245. * Fetch a result row as an object
  246. *
  247. * @param resource $res Raw result
  248. * @return stdClass
  249. */
  250. abstract protected function mysqlFetchObject( $res );
  251. /**
  252. * @param IResultWrapper|resource $res
  253. * @return array|bool
  254. * @throws DBUnexpectedError
  255. */
  256. public function fetchRow( $res ) {
  257. AtEase::suppressWarnings();
  258. $row = $this->mysqlFetchArray( ResultWrapper::unwrap( $res ) );
  259. AtEase::restoreWarnings();
  260. $errno = $this->lastErrno();
  261. // Unfortunately, mysql_fetch_array does not reset the last errno.
  262. // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
  263. // these are the only errors mysql_fetch_array can cause.
  264. // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
  265. if ( $errno == 2000 || $errno == 2013 ) {
  266. throw new DBUnexpectedError(
  267. $this,
  268. 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
  269. );
  270. }
  271. return $row;
  272. }
  273. /**
  274. * Fetch a result row as an associative and numeric array
  275. *
  276. * @param resource $res Raw result
  277. * @return array|false
  278. */
  279. abstract protected function mysqlFetchArray( $res );
  280. /**
  281. * @throws DBUnexpectedError
  282. * @param IResultWrapper|resource $res
  283. * @return int
  284. */
  285. function numRows( $res ) {
  286. if ( is_bool( $res ) ) {
  287. $n = 0;
  288. } else {
  289. AtEase::suppressWarnings();
  290. $n = $this->mysqlNumRows( ResultWrapper::unwrap( $res ) );
  291. AtEase::restoreWarnings();
  292. }
  293. // Unfortunately, mysql_num_rows does not reset the last errno.
  294. // We are not checking for any errors here, since
  295. // there are no errors mysql_num_rows can cause.
  296. // See https://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
  297. // See https://phabricator.wikimedia.org/T44430
  298. return $n;
  299. }
  300. /**
  301. * Get number of rows in result
  302. *
  303. * @param resource $res Raw result
  304. * @return int
  305. */
  306. abstract protected function mysqlNumRows( $res );
  307. /**
  308. * @param IResultWrapper|resource $res
  309. * @return int
  310. */
  311. public function numFields( $res ) {
  312. return $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
  313. }
  314. /**
  315. * Get number of fields in result
  316. *
  317. * @param resource $res Raw result
  318. * @return int
  319. */
  320. abstract protected function mysqlNumFields( $res );
  321. /**
  322. * @param IResultWrapper|resource $res
  323. * @param int $n
  324. * @return string
  325. */
  326. public function fieldName( $res, $n ) {
  327. return $this->mysqlFieldName( ResultWrapper::unwrap( $res ), $n );
  328. }
  329. /**
  330. * Get the name of the specified field in a result
  331. *
  332. * @param IResultWrapper|resource $res
  333. * @param int $n
  334. * @return string
  335. */
  336. abstract protected function mysqlFieldName( $res, $n );
  337. /**
  338. * mysql_field_type() wrapper
  339. * @param IResultWrapper|resource $res
  340. * @param int $n
  341. * @return string
  342. */
  343. public function fieldType( $res, $n ) {
  344. return $this->mysqlFieldType( ResultWrapper::unwrap( $res ), $n );
  345. }
  346. /**
  347. * Get the type of the specified field in a result
  348. *
  349. * @param IResultWrapper|resource $res
  350. * @param int $n
  351. * @return string
  352. */
  353. abstract protected function mysqlFieldType( $res, $n );
  354. /**
  355. * @param IResultWrapper|resource $res
  356. * @param int $row
  357. * @return bool
  358. */
  359. public function dataSeek( $res, $row ) {
  360. return $this->mysqlDataSeek( ResultWrapper::unwrap( $res ), $row );
  361. }
  362. /**
  363. * Move internal result pointer
  364. *
  365. * @param IResultWrapper|resource $res
  366. * @param int $row
  367. * @return bool
  368. */
  369. abstract protected function mysqlDataSeek( $res, $row );
  370. /**
  371. * @return string
  372. */
  373. public function lastError() {
  374. if ( $this->conn ) {
  375. # Even if it's non-zero, it can still be invalid
  376. AtEase::suppressWarnings();
  377. $error = $this->mysqlError( $this->conn );
  378. if ( !$error ) {
  379. $error = $this->mysqlError();
  380. }
  381. AtEase::restoreWarnings();
  382. } else {
  383. $error = $this->mysqlError();
  384. }
  385. if ( $error ) {
  386. $error .= ' (' . $this->server . ')';
  387. }
  388. return $error;
  389. }
  390. /**
  391. * Returns the text of the error message from previous MySQL operation
  392. *
  393. * @param resource|null $conn Raw connection
  394. * @return string
  395. */
  396. abstract protected function mysqlError( $conn = null );
  397. protected function wasQueryTimeout( $error, $errno ) {
  398. // https://dev.mysql.com/doc/refman/8.0/en/client-error-reference.html
  399. // https://phabricator.wikimedia.org/T170638
  400. return in_array( $errno, [ 2062, 3024 ] );
  401. }
  402. public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
  403. $this->nativeReplace( $table, $rows, $fname );
  404. }
  405. protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
  406. $row = $this->getReplicationSafetyInfo();
  407. // For row-based-replication, the resulting changes will be relayed, not the query
  408. if ( $row->binlog_format === 'ROW' ) {
  409. return true;
  410. }
  411. // LIMIT requires ORDER BY on a unique key or it is non-deterministic
  412. if ( isset( $selectOptions['LIMIT'] ) ) {
  413. return false;
  414. }
  415. // In MySQL, an INSERT SELECT is only replication safe with row-based
  416. // replication or if innodb_autoinc_lock_mode is 0. When those
  417. // conditions aren't met, use non-native mode.
  418. // While we could try to determine if the insert is safe anyway by
  419. // checking if the target table has an auto-increment column that
  420. // isn't set in $varMap, that seems unlikely to be worth the extra
  421. // complexity.
  422. return (
  423. in_array( 'NO_AUTO_COLUMNS', $insertOptions ) ||
  424. (int)$row->innodb_autoinc_lock_mode === 0
  425. );
  426. }
  427. /**
  428. * @return stdClass Process cached row
  429. */
  430. protected function getReplicationSafetyInfo() {
  431. if ( $this->replicationInfoRow === null ) {
  432. $this->replicationInfoRow = $this->selectRow(
  433. false,
  434. [
  435. 'innodb_autoinc_lock_mode' => '@@innodb_autoinc_lock_mode',
  436. 'binlog_format' => '@@binlog_format',
  437. ],
  438. [],
  439. __METHOD__
  440. );
  441. }
  442. return $this->replicationInfoRow;
  443. }
  444. /**
  445. * Estimate rows in dataset
  446. * Returns estimated count, based on EXPLAIN output
  447. * Takes same arguments as Database::select()
  448. *
  449. * @param string|array $table
  450. * @param string|array $var
  451. * @param string|array $conds
  452. * @param string $fname
  453. * @param string|array $options
  454. * @param array $join_conds
  455. * @return bool|int
  456. */
  457. public function estimateRowCount( $table, $var = '*', $conds = '',
  458. $fname = __METHOD__, $options = [], $join_conds = []
  459. ) {
  460. $conds = $this->normalizeConditions( $conds, $fname );
  461. $column = $this->extractSingleFieldFromList( $var );
  462. if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
  463. $conds[] = "$column IS NOT NULL";
  464. }
  465. $options['EXPLAIN'] = true;
  466. $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
  467. if ( $res === false ) {
  468. return false;
  469. }
  470. if ( !$this->numRows( $res ) ) {
  471. return 0;
  472. }
  473. $rows = 1;
  474. foreach ( $res as $plan ) {
  475. $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
  476. }
  477. return (int)$rows;
  478. }
  479. public function tableExists( $table, $fname = __METHOD__ ) {
  480. // Split database and table into proper variables as Database::tableName() returns
  481. // shared tables prefixed with their database, which do not work in SHOW TABLES statements
  482. list( $database, , $prefix, $table ) = $this->qualifiedTableComponents( $table );
  483. $tableName = "{$prefix}{$table}";
  484. if ( isset( $this->sessionTempTables[$tableName] ) ) {
  485. return true; // already known to exist and won't show in SHOW TABLES anyway
  486. }
  487. // We can't use buildLike() here, because it specifies an escape character
  488. // other than the backslash, which is the only one supported by SHOW TABLES
  489. $encLike = $this->escapeLikeInternal( $tableName, '\\' );
  490. // If the database has been specified (such as for shared tables), use "FROM"
  491. if ( $database !== '' ) {
  492. $encDatabase = $this->addIdentifierQuotes( $database );
  493. $query = "SHOW TABLES FROM $encDatabase LIKE '$encLike'";
  494. } else {
  495. $query = "SHOW TABLES LIKE '$encLike'";
  496. }
  497. return $this->query( $query, $fname )->numRows() > 0;
  498. }
  499. /**
  500. * @param string $table
  501. * @param string $field
  502. * @return bool|MySQLField
  503. */
  504. public function fieldInfo( $table, $field ) {
  505. $table = $this->tableName( $table );
  506. $flags = self::QUERY_SILENCE_ERRORS;
  507. $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, $flags );
  508. if ( !$res ) {
  509. return false;
  510. }
  511. $n = $this->mysqlNumFields( ResultWrapper::unwrap( $res ) );
  512. for ( $i = 0; $i < $n; $i++ ) {
  513. $meta = $this->mysqlFetchField( ResultWrapper::unwrap( $res ), $i );
  514. if ( $field == $meta->name ) {
  515. return new MySQLField( $meta );
  516. }
  517. }
  518. return false;
  519. }
  520. /**
  521. * Get column information from a result
  522. *
  523. * @param resource $res Raw result
  524. * @param int $n
  525. * @return stdClass
  526. */
  527. abstract protected function mysqlFetchField( $res, $n );
  528. /**
  529. * Get information about an index into an object
  530. * Returns false if the index does not exist
  531. *
  532. * @param string $table
  533. * @param string $index
  534. * @param string $fname
  535. * @return bool|array|null False or null on failure
  536. */
  537. public function indexInfo( $table, $index, $fname = __METHOD__ ) {
  538. # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
  539. # SHOW INDEX should work for 3.x and up:
  540. # https://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
  541. $table = $this->tableName( $table );
  542. $index = $this->indexName( $index );
  543. $sql = 'SHOW INDEX FROM ' . $table;
  544. $res = $this->query( $sql, $fname );
  545. if ( !$res ) {
  546. return null;
  547. }
  548. $result = [];
  549. foreach ( $res as $row ) {
  550. if ( $row->Key_name == $index ) {
  551. $result[] = $row;
  552. }
  553. }
  554. return $result ?: false;
  555. }
  556. /**
  557. * @param string $s
  558. * @return string
  559. */
  560. public function strencode( $s ) {
  561. return $this->mysqlRealEscapeString( $s );
  562. }
  563. /**
  564. * @param string $s
  565. * @return mixed
  566. */
  567. abstract protected function mysqlRealEscapeString( $s );
  568. public function addQuotes( $s ) {
  569. if ( is_bool( $s ) ) {
  570. // Parent would transform to int, which does not play nice with MySQL type juggling.
  571. // When searching for an int in a string column, the strings are cast to int, which
  572. // means false would match any string not starting with a number.
  573. $s = (string)(int)$s;
  574. }
  575. return parent::addQuotes( $s );
  576. }
  577. /**
  578. * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
  579. *
  580. * @param string $s
  581. * @return string
  582. */
  583. public function addIdentifierQuotes( $s ) {
  584. // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
  585. // Remove NUL bytes and escape backticks by doubling
  586. return '`' . str_replace( [ "\0", '`' ], [ '', '``' ], $s ) . '`';
  587. }
  588. /**
  589. * @param string $name
  590. * @return bool
  591. */
  592. public function isQuotedIdentifier( $name ) {
  593. return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
  594. }
  595. protected function doGetLag() {
  596. if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
  597. return $this->getLagFromPtHeartbeat();
  598. } else {
  599. return $this->getLagFromSlaveStatus();
  600. }
  601. }
  602. /**
  603. * @return string
  604. */
  605. protected function getLagDetectionMethod() {
  606. return $this->lagDetectionMethod;
  607. }
  608. /**
  609. * @return bool|int
  610. */
  611. protected function getLagFromSlaveStatus() {
  612. $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX;
  613. $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__, $flags );
  614. $row = $res ? $res->fetchObject() : false;
  615. // If the server is not replicating, there will be no row
  616. if ( $row && strval( $row->Seconds_Behind_Master ) !== '' ) {
  617. return intval( $row->Seconds_Behind_Master );
  618. }
  619. return false;
  620. }
  621. /**
  622. * @return bool|float
  623. */
  624. protected function getLagFromPtHeartbeat() {
  625. $options = $this->lagDetectionOptions;
  626. $currentTrxInfo = $this->getRecordedTransactionLagStatus();
  627. if ( $currentTrxInfo ) {
  628. // There is an active transaction and the initial lag was already queried
  629. $staleness = microtime( true ) - $currentTrxInfo['since'];
  630. if ( $staleness > self::LAG_STALE_WARN_THRESHOLD ) {
  631. // Avoid returning higher and higher lag value due to snapshot age
  632. // given that the isolation level will typically be REPEATABLE-READ
  633. $this->queryLogger->warning(
  634. "Using cached lag value for {db_server} due to active transaction",
  635. $this->getLogContext( [
  636. 'method' => __METHOD__,
  637. 'age' => $staleness,
  638. 'exception' => new RuntimeException()
  639. ] )
  640. );
  641. }
  642. return $currentTrxInfo['lag'];
  643. }
  644. if ( isset( $options['conds'] ) ) {
  645. // Best method for multi-DC setups: use logical channel names
  646. $data = $this->getHeartbeatData( $options['conds'] );
  647. } else {
  648. // Standard method: use master server ID (works with stock pt-heartbeat)
  649. $masterInfo = $this->getMasterServerInfo();
  650. if ( !$masterInfo ) {
  651. $this->queryLogger->error(
  652. "Unable to query master of {db_server} for server ID",
  653. $this->getLogContext( [
  654. 'method' => __METHOD__
  655. ] )
  656. );
  657. return false; // could not get master server ID
  658. }
  659. $conds = [ 'server_id' => intval( $masterInfo['serverId'] ) ];
  660. $data = $this->getHeartbeatData( $conds );
  661. }
  662. list( $time, $nowUnix ) = $data;
  663. if ( $time !== null ) {
  664. // @time is in ISO format like "2015-09-25T16:48:10.000510"
  665. $dateTime = new DateTime( $time, new DateTimeZone( 'UTC' ) );
  666. $timeUnix = (int)$dateTime->format( 'U' ) + $dateTime->format( 'u' ) / 1e6;
  667. return max( $nowUnix - $timeUnix, 0.0 );
  668. }
  669. $this->queryLogger->error(
  670. "Unable to find pt-heartbeat row for {db_server}",
  671. $this->getLogContext( [
  672. 'method' => __METHOD__
  673. ] )
  674. );
  675. return false;
  676. }
  677. protected function getMasterServerInfo() {
  678. $cache = $this->srvCache;
  679. $key = $cache->makeGlobalKey(
  680. 'mysql',
  681. 'master-info',
  682. // Using one key for all cluster replica DBs is preferable
  683. $this->getLBInfo( 'clusterMasterHost' ) ?: $this->getServer()
  684. );
  685. $fname = __METHOD__;
  686. return $cache->getWithSetCallback(
  687. $key,
  688. $cache::TTL_INDEFINITE,
  689. function () use ( $cache, $key, $fname ) {
  690. // Get and leave a lock key in place for a short period
  691. if ( !$cache->lock( $key, 0, 10 ) ) {
  692. return false; // avoid master connection spike slams
  693. }
  694. $conn = $this->getLazyMasterHandle();
  695. if ( !$conn ) {
  696. return false; // something is misconfigured
  697. }
  698. // Connect to and query the master; catch errors to avoid outages
  699. try {
  700. $flags = self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX;
  701. $res = $conn->query( 'SELECT @@server_id AS id', $fname, $flags );
  702. $row = $res ? $res->fetchObject() : false;
  703. $id = $row ? (int)$row->id : 0;
  704. } catch ( DBError $e ) {
  705. $id = 0;
  706. }
  707. // Cache the ID if it was retrieved
  708. return $id ? [ 'serverId' => $id, 'asOf' => time() ] : false;
  709. }
  710. );
  711. }
  712. /**
  713. * @param array $conds WHERE clause conditions to find a row
  714. * @return array (heartbeat `ts` column value or null, UNIX timestamp) for the newest beat
  715. * @see https://www.percona.com/doc/percona-toolkit/2.1/pt-heartbeat.html
  716. */
  717. protected function getHeartbeatData( array $conds ) {
  718. // Query time and trip time are not counted
  719. $nowUnix = microtime( true );
  720. $whereSQL = $this->makeList( $conds, self::LIST_AND );
  721. // Use ORDER BY for channel based queries since that field might not be UNIQUE.
  722. // Note: this would use "TIMESTAMPDIFF(MICROSECOND,ts,UTC_TIMESTAMP(6))" but the
  723. // percision field is not supported in MySQL <= 5.5.
  724. $res = $this->query(
  725. "SELECT ts FROM heartbeat.heartbeat WHERE $whereSQL ORDER BY ts DESC LIMIT 1",
  726. __METHOD__,
  727. self::QUERY_SILENCE_ERRORS | self::QUERY_IGNORE_DBO_TRX
  728. );
  729. $row = $res ? $res->fetchObject() : false;
  730. return [ $row ? $row->ts : null, $nowUnix ];
  731. }
  732. protected function getApproximateLagStatus() {
  733. if ( $this->getLagDetectionMethod() === 'pt-heartbeat' ) {
  734. // Disable caching since this is fast enough and we don't wan't
  735. // to be *too* pessimistic by having both the cache TTL and the
  736. // pt-heartbeat interval count as lag in getSessionLagStatus()
  737. return parent::getApproximateLagStatus();
  738. }
  739. $key = $this->srvCache->makeGlobalKey( 'mysql-lag', $this->getServer() );
  740. $approxLag = $this->srvCache->get( $key );
  741. if ( !$approxLag ) {
  742. $approxLag = parent::getApproximateLagStatus();
  743. $this->srvCache->set( $key, $approxLag, 1 );
  744. }
  745. return $approxLag;
  746. }
  747. public function masterPosWait( DBMasterPos $pos, $timeout ) {
  748. if ( !( $pos instanceof MySQLMasterPos ) ) {
  749. throw new InvalidArgumentException( "Position not an instance of MySQLMasterPos" );
  750. }
  751. if ( $this->getLBInfo( 'is static' ) === true ) {
  752. $this->queryLogger->debug(
  753. "Bypassed replication wait; database has a static dataset",
  754. $this->getLogContext( [ 'method' => __METHOD__ ] )
  755. );
  756. return 0; // this is a copy of a read-only dataset with no master DB
  757. } elseif ( $this->lastKnownReplicaPos && $this->lastKnownReplicaPos->hasReached( $pos ) ) {
  758. $this->queryLogger->debug(
  759. "Bypassed replication wait; replication already known to have reached $pos",
  760. $this->getLogContext( [ 'method' => __METHOD__ ] )
  761. );
  762. return 0; // already reached this point for sure
  763. }
  764. // Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
  765. if ( $pos->getGTIDs() ) {
  766. // Get the GTIDs from this replica server too see the domains (channels)
  767. $refPos = $this->getReplicaPos();
  768. if ( !$refPos ) {
  769. $this->queryLogger->error(
  770. "Could not get replication position",
  771. $this->getLogContext( [ 'method' => __METHOD__ ] )
  772. );
  773. return -1; // this is the master itself?
  774. }
  775. // GTIDs with domains (channels) that are active and are present on the replica
  776. $gtidsWait = $pos::getRelevantActiveGTIDs( $pos, $refPos );
  777. if ( !$gtidsWait ) {
  778. $this->queryLogger->error(
  779. "No active GTIDs in $pos share a domain with those in $refPos",
  780. $this->getLogContext( [ 'method' => __METHOD__, 'activeDomain' => $pos ] )
  781. );
  782. return -1; // $pos is from the wrong cluster?
  783. }
  784. // Wait on the GTID set
  785. $gtidArg = $this->addQuotes( implode( ',', $gtidsWait ) );
  786. if ( strpos( $gtidArg, ':' ) !== false ) {
  787. // MySQL GTIDs, e.g "source_id:transaction_id"
  788. $sql = "SELECT WAIT_FOR_EXECUTED_GTID_SET($gtidArg, $timeout)";
  789. } else {
  790. // MariaDB GTIDs, e.g."domain:server:sequence"
  791. $sql = "SELECT MASTER_GTID_WAIT($gtidArg, $timeout)";
  792. }
  793. } else {
  794. // Wait on the binlog coordinates
  795. $encFile = $this->addQuotes( $pos->getLogFile() );
  796. $encPos = intval( $pos->getLogPosition()[$pos::CORD_EVENT] );
  797. $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
  798. }
  799. $res = $this->query( $sql, __METHOD__, self::QUERY_IGNORE_DBO_TRX );
  800. $row = $this->fetchRow( $res );
  801. // Result can be NULL (error), -1 (timeout), or 0+ per the MySQL manual
  802. $status = ( $row[0] !== null ) ? intval( $row[0] ) : null;
  803. if ( $status === null ) {
  804. $this->queryLogger->error(
  805. "An error occurred while waiting for replication to reach $pos",
  806. $this->getLogContext( [ 'method' => __METHOD__, 'sql' => $sql ] )
  807. );
  808. } elseif ( $status < 0 ) {
  809. $this->queryLogger->error(
  810. "Timed out waiting for replication to reach $pos",
  811. $this->getLogContext( [
  812. 'method' => __METHOD__, 'sql' => $sql, 'timeout' => $timeout
  813. ] )
  814. );
  815. } elseif ( $status >= 0 ) {
  816. $this->queryLogger->debug(
  817. "Replication has reached $pos",
  818. $this->getLogContext( [ 'method' => __METHOD__ ] )
  819. );
  820. // Remember that this position was reached to save queries next time
  821. $this->lastKnownReplicaPos = $pos;
  822. }
  823. return $status;
  824. }
  825. /**
  826. * Get the position of the master from SHOW SLAVE STATUS
  827. *
  828. * @return MySQLMasterPos|bool
  829. */
  830. public function getReplicaPos() {
  831. $now = microtime( true ); // as-of-time *before* fetching GTID variables
  832. if ( $this->useGTIDs() ) {
  833. // Try to use GTIDs, fallbacking to binlog positions if not possible
  834. $data = $this->getServerGTIDs( __METHOD__ );
  835. // Use gtid_slave_pos for MariaDB and gtid_executed for MySQL
  836. foreach ( [ 'gtid_slave_pos', 'gtid_executed' ] as $name ) {
  837. if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
  838. return new MySQLMasterPos( $data[$name], $now );
  839. }
  840. }
  841. }
  842. $data = $this->getServerRoleStatus( 'SLAVE', __METHOD__ );
  843. if ( $data && strlen( $data['Relay_Master_Log_File'] ) ) {
  844. return new MySQLMasterPos(
  845. "{$data['Relay_Master_Log_File']}/{$data['Exec_Master_Log_Pos']}",
  846. $now
  847. );
  848. }
  849. return false;
  850. }
  851. /**
  852. * Get the position of the master from SHOW MASTER STATUS
  853. *
  854. * @return MySQLMasterPos|bool
  855. */
  856. public function getMasterPos() {
  857. $now = microtime( true ); // as-of-time *before* fetching GTID variables
  858. $pos = false;
  859. if ( $this->useGTIDs() ) {
  860. // Try to use GTIDs, fallbacking to binlog positions if not possible
  861. $data = $this->getServerGTIDs( __METHOD__ );
  862. // Use gtid_binlog_pos for MariaDB and gtid_executed for MySQL
  863. foreach ( [ 'gtid_binlog_pos', 'gtid_executed' ] as $name ) {
  864. if ( isset( $data[$name] ) && strlen( $data[$name] ) ) {
  865. $pos = new MySQLMasterPos( $data[$name], $now );
  866. break;
  867. }
  868. }
  869. // Filter domains that are inactive or not relevant to the session
  870. if ( $pos ) {
  871. $pos->setActiveOriginServerId( $this->getServerId() );
  872. $pos->setActiveOriginServerUUID( $this->getServerUUID() );
  873. if ( isset( $data['gtid_domain_id'] ) ) {
  874. $pos->setActiveDomain( $data['gtid_domain_id'] );
  875. }
  876. }
  877. }
  878. if ( !$pos ) {
  879. $data = $this->getServerRoleStatus( 'MASTER', __METHOD__ );
  880. if ( $data && strlen( $data['File'] ) ) {
  881. $pos = new MySQLMasterPos( "{$data['File']}/{$data['Position']}", $now );
  882. }
  883. }
  884. return $pos;
  885. }
  886. /**
  887. * @return int
  888. * @throws DBQueryError If the variable doesn't exist for some reason
  889. */
  890. protected function getServerId() {
  891. $fname = __METHOD__;
  892. return $this->srvCache->getWithSetCallback(
  893. $this->srvCache->makeGlobalKey( 'mysql-server-id', $this->getServer() ),
  894. self::SERVER_ID_CACHE_TTL,
  895. function () use ( $fname ) {
  896. $flags = self::QUERY_IGNORE_DBO_TRX;
  897. $res = $this->query( "SELECT @@server_id AS id", $fname, $flags );
  898. return intval( $this->fetchObject( $res )->id );
  899. }
  900. );
  901. }
  902. /**
  903. * @return string|null
  904. */
  905. protected function getServerUUID() {
  906. $fname = __METHOD__;
  907. return $this->srvCache->getWithSetCallback(
  908. $this->srvCache->makeGlobalKey( 'mysql-server-uuid', $this->getServer() ),
  909. self::SERVER_ID_CACHE_TTL,
  910. function () use ( $fname ) {
  911. $flags = self::QUERY_IGNORE_DBO_TRX;
  912. $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'server_uuid'", $fname, $flags );
  913. $row = $this->fetchObject( $res );
  914. return $row ? $row->Value : null;
  915. }
  916. );
  917. }
  918. /**
  919. * @param string $fname
  920. * @return string[]
  921. */
  922. protected function getServerGTIDs( $fname = __METHOD__ ) {
  923. $map = [];
  924. $flags = self::QUERY_IGNORE_DBO_TRX;
  925. // Get global-only variables like gtid_executed
  926. $res = $this->query( "SHOW GLOBAL VARIABLES LIKE 'gtid_%'", $fname, $flags );
  927. foreach ( $res as $row ) {
  928. $map[$row->Variable_name] = $row->Value;
  929. }
  930. // Get session-specific (e.g. gtid_domain_id since that is were writes will log)
  931. $res = $this->query( "SHOW SESSION VARIABLES LIKE 'gtid_%'", $fname, $flags );
  932. foreach ( $res as $row ) {
  933. $map[$row->Variable_name] = $row->Value;
  934. }
  935. return $map;
  936. }
  937. /**
  938. * @param string $role One of "MASTER"/"SLAVE"
  939. * @param string $fname
  940. * @return string[] Latest available server status row
  941. */
  942. protected function getServerRoleStatus( $role, $fname = __METHOD__ ) {
  943. $flags = self::QUERY_IGNORE_DBO_TRX;
  944. return $this->query( "SHOW $role STATUS", $fname, $flags )->fetchRow() ?: [];
  945. }
  946. public function serverIsReadOnly() {
  947. // Avoid SHOW to avoid internal temporary tables
  948. $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS;
  949. $res = $this->query( "SELECT @@GLOBAL.read_only AS Value", __METHOD__, $flags );
  950. $row = $this->fetchObject( $res );
  951. return $row ? (bool)$row->Value : false;
  952. }
  953. /**
  954. * @param string $index
  955. * @return string
  956. */
  957. function useIndexClause( $index ) {
  958. return "FORCE INDEX (" . $this->indexName( $index ) . ")";
  959. }
  960. /**
  961. * @param string $index
  962. * @return string
  963. */
  964. function ignoreIndexClause( $index ) {
  965. return "IGNORE INDEX (" . $this->indexName( $index ) . ")";
  966. }
  967. /**
  968. * @return string
  969. */
  970. public function getSoftwareLink() {
  971. // MariaDB includes its name in its version string; this is how MariaDB's version of
  972. // the mysql command-line client identifies MariaDB servers (see mariadb_connection()
  973. // in libmysql/libmysql.c).
  974. $version = $this->getServerVersion();
  975. if ( strpos( $version, 'MariaDB' ) !== false || strpos( $version, '-maria-' ) !== false ) {
  976. return '[{{int:version-db-mariadb-url}} MariaDB]';
  977. }
  978. // Percona Server's version suffix is not very distinctive, and @@version_comment
  979. // doesn't give the necessary info for source builds, so assume the server is MySQL.
  980. // (Even Percona's version of mysql doesn't try to make the distinction.)
  981. return '[{{int:version-db-mysql-url}} MySQL]';
  982. }
  983. /**
  984. * @return string
  985. */
  986. public function getServerVersion() {
  987. $cache = $this->srvCache;
  988. $fname = __METHOD__;
  989. return $cache->getWithSetCallback(
  990. $cache->makeGlobalKey( 'mysql-server-version', $this->getServer() ),
  991. $cache::TTL_HOUR,
  992. function () use ( $fname ) {
  993. // Not using mysql_get_server_info() or similar for consistency: in the handshake,
  994. // MariaDB 10 adds the prefix "5.5.5-", and only some newer client libraries strip
  995. // it off (see RPL_VERSION_HACK in include/mysql_com.h).
  996. return $this->selectField( '', 'VERSION()', '', $fname );
  997. }
  998. );
  999. }
  1000. /**
  1001. * @param array $options
  1002. */
  1003. public function setSessionOptions( array $options ) {
  1004. if ( isset( $options['connTimeout'] ) ) {
  1005. $flags = self::QUERY_IGNORE_DBO_TRX;
  1006. $timeout = (int)$options['connTimeout'];
  1007. $this->query( "SET net_read_timeout=$timeout", __METHOD__, $flags );
  1008. $this->query( "SET net_write_timeout=$timeout", __METHOD__, $flags );
  1009. }
  1010. }
  1011. /**
  1012. * @param string &$sql
  1013. * @param string &$newLine
  1014. * @return bool
  1015. */
  1016. public function streamStatementEnd( &$sql, &$newLine ) {
  1017. if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
  1018. preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
  1019. $this->delimiter = $m[1];
  1020. $newLine = '';
  1021. }
  1022. return parent::streamStatementEnd( $sql, $newLine );
  1023. }
  1024. /**
  1025. * Check to see if a named lock is available. This is non-blocking.
  1026. *
  1027. * @param string $lockName Name of lock to poll
  1028. * @param string $method Name of method calling us
  1029. * @return bool
  1030. * @since 1.20
  1031. */
  1032. public function lockIsFree( $lockName, $method ) {
  1033. if ( !parent::lockIsFree( $lockName, $method ) ) {
  1034. return false; // already held
  1035. }
  1036. $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
  1037. $flags = self::QUERY_IGNORE_DBO_TRX;
  1038. $res = $this->query( "SELECT IS_FREE_LOCK($encName) AS lockstatus", $method, $flags );
  1039. $row = $this->fetchObject( $res );
  1040. return ( $row->lockstatus == 1 );
  1041. }
  1042. /**
  1043. * @param string $lockName
  1044. * @param string $method
  1045. * @param int $timeout
  1046. * @return bool
  1047. */
  1048. public function lock( $lockName, $method, $timeout = 5 ) {
  1049. $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
  1050. $flags = self::QUERY_IGNORE_DBO_TRX;
  1051. $res = $this->query( "SELECT GET_LOCK($encName, $timeout) AS lockstatus", $method, $flags );
  1052. $row = $this->fetchObject( $res );
  1053. if ( $row->lockstatus == 1 ) {
  1054. parent::lock( $lockName, $method, $timeout ); // record
  1055. return true;
  1056. }
  1057. $this->queryLogger->info( __METHOD__ . " failed to acquire lock '{lockname}'",
  1058. [ 'lockname' => $lockName ] );
  1059. return false;
  1060. }
  1061. /**
  1062. * FROM MYSQL DOCS:
  1063. * https://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
  1064. * @param string $lockName
  1065. * @param string $method
  1066. * @return bool
  1067. */
  1068. public function unlock( $lockName, $method ) {
  1069. $encName = $this->addQuotes( $this->makeLockName( $lockName ) );
  1070. $flags = self::QUERY_IGNORE_DBO_TRX;
  1071. $res = $this->query( "SELECT RELEASE_LOCK($encName) as lockstatus", $method, $flags );
  1072. $row = $this->fetchObject( $res );
  1073. if ( $row->lockstatus == 1 ) {
  1074. parent::unlock( $lockName, $method ); // record
  1075. return true;
  1076. }
  1077. $this->queryLogger->warning( __METHOD__ . " failed to release lock '$lockName'\n" );
  1078. return false;
  1079. }
  1080. private function makeLockName( $lockName ) {
  1081. // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
  1082. // Newer version enforce a 64 char length limit.
  1083. return ( strlen( $lockName ) > 64 ) ? sha1( $lockName ) : $lockName;
  1084. }
  1085. public function namedLocksEnqueue() {
  1086. return true;
  1087. }
  1088. public function tableLocksHaveTransactionScope() {
  1089. return false; // tied to TCP connection
  1090. }
  1091. protected function doLockTables( array $read, array $write, $method ) {
  1092. $items = [];
  1093. foreach ( $write as $table ) {
  1094. $items[] = $this->tableName( $table ) . ' WRITE';
  1095. }
  1096. foreach ( $read as $table ) {
  1097. $items[] = $this->tableName( $table ) . ' READ';
  1098. }
  1099. $sql = "LOCK TABLES " . implode( ',', $items );
  1100. $this->query( $sql, $method, self::QUERY_IGNORE_DBO_TRX );
  1101. return true;
  1102. }
  1103. protected function doUnlockTables( $method ) {
  1104. $this->query( "UNLOCK TABLES", $method, self::QUERY_IGNORE_DBO_TRX );
  1105. return true;
  1106. }
  1107. /**
  1108. * @param bool $value
  1109. */
  1110. public function setBigSelects( $value = true ) {
  1111. if ( $value === 'default' ) {
  1112. if ( $this->defaultBigSelects === null ) {
  1113. # Function hasn't been called before so it must already be set to the default
  1114. return;
  1115. } else {
  1116. $value = $this->defaultBigSelects;
  1117. }
  1118. } elseif ( $this->defaultBigSelects === null ) {
  1119. $this->defaultBigSelects =
  1120. (bool)$this->selectField( false, '@@sql_big_selects', '', __METHOD__ );
  1121. }
  1122. $encValue = $value ? '1' : '0';
  1123. $this->query( "SET sql_big_selects=$encValue", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
  1124. }
  1125. /**
  1126. * DELETE where the condition is a join. MySql uses multi-table deletes.
  1127. * @param string $delTable
  1128. * @param string $joinTable
  1129. * @param string $delVar
  1130. * @param string $joinVar
  1131. * @param array|string $conds
  1132. * @param bool|string $fname
  1133. * @throws DBUnexpectedError
  1134. */
  1135. public function deleteJoin(
  1136. $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
  1137. ) {
  1138. if ( !$conds ) {
  1139. throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
  1140. }
  1141. $delTable = $this->tableName( $delTable );
  1142. $joinTable = $this->tableName( $joinTable );
  1143. $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
  1144. if ( $conds != '*' ) {
  1145. $sql .= ' AND ' . $this->makeList( $conds, self::LIST_AND );
  1146. }
  1147. $this->query( $sql, $fname );
  1148. }
  1149. public function upsert(
  1150. $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
  1151. ) {
  1152. if ( $rows === [] ) {
  1153. return true; // nothing to do
  1154. }
  1155. if ( !is_array( reset( $rows ) ) ) {
  1156. $rows = [ $rows ];
  1157. }
  1158. $table = $this->tableName( $table );
  1159. $columns = array_keys( $rows[0] );
  1160. $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
  1161. $rowTuples = [];
  1162. foreach ( $rows as $row ) {
  1163. $rowTuples[] = '(' . $this->makeList( $row ) . ')';
  1164. }
  1165. $sql .= implode( ',', $rowTuples );
  1166. $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, self::LIST_SET );
  1167. $this->query( $sql, $fname );
  1168. return true;
  1169. }
  1170. /**
  1171. * Determines how long the server has been up
  1172. *
  1173. * @return int
  1174. */
  1175. public function getServerUptime() {
  1176. $vars = $this->getMysqlStatus( 'Uptime' );
  1177. return (int)$vars['Uptime'];
  1178. }
  1179. /**
  1180. * Determines if the last failure was due to a deadlock
  1181. *
  1182. * @return bool
  1183. */
  1184. public function wasDeadlock() {
  1185. return $this->lastErrno() == 1213;
  1186. }
  1187. /**
  1188. * Determines if the last failure was due to a lock timeout
  1189. *
  1190. * @return bool
  1191. */
  1192. public function wasLockTimeout() {
  1193. return $this->lastErrno() == 1205;
  1194. }
  1195. /**
  1196. * Determines if the last failure was due to the database being read-only.
  1197. *
  1198. * @return bool
  1199. */
  1200. public function wasReadOnlyError() {
  1201. return $this->lastErrno() == 1223 ||
  1202. ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
  1203. }
  1204. public function wasConnectionError( $errno ) {
  1205. return $errno == 2013 || $errno == 2006;
  1206. }
  1207. protected function wasKnownStatementRollbackError() {
  1208. $errno = $this->lastErrno();
  1209. if ( $errno === 1205 ) { // lock wait timeout
  1210. // Note that this is uncached to avoid stale values of SET is used
  1211. $row = $this->selectRow(
  1212. false,
  1213. [ 'innodb_rollback_on_timeout' => '@@innodb_rollback_on_timeout' ],
  1214. [],
  1215. __METHOD__
  1216. );
  1217. // https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
  1218. // https://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html
  1219. return $row->innodb_rollback_on_timeout ? false : true;
  1220. }
  1221. // See https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
  1222. return in_array( $errno, [ 1022, 1062, 1216, 1217, 1137, 1146, 1051, 1054 ], true );
  1223. }
  1224. /**
  1225. * @param string $oldName
  1226. * @param string $newName
  1227. * @param bool $temporary
  1228. * @param string $fname
  1229. * @return bool
  1230. */
  1231. public function duplicateTableStructure(
  1232. $oldName, $newName, $temporary = false, $fname = __METHOD__
  1233. ) {
  1234. $tmp = $temporary ? 'TEMPORARY ' : '';
  1235. $newName = $this->addIdentifierQuotes( $newName );
  1236. $oldName = $this->addIdentifierQuotes( $oldName );
  1237. $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
  1238. return $this->query( $query, $fname, $this::QUERY_PSEUDO_PERMANENT );
  1239. }
  1240. /**
  1241. * List all tables on the database
  1242. *
  1243. * @param string|null $prefix Only show tables with this prefix, e.g. mw_
  1244. * @param string $fname Calling function name
  1245. * @return array
  1246. */
  1247. public function listTables( $prefix = null, $fname = __METHOD__ ) {
  1248. $result = $this->query( "SHOW TABLES", $fname );
  1249. $endArray = [];
  1250. foreach ( $result as $table ) {
  1251. $vars = get_object_vars( $table );
  1252. $table = array_pop( $vars );
  1253. if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
  1254. $endArray[] = $table;
  1255. }
  1256. }
  1257. return $endArray;
  1258. }
  1259. /**
  1260. * @param string $tableName
  1261. * @param string $fName
  1262. * @return bool|IResultWrapper
  1263. */
  1264. public function dropTable( $tableName, $fName = __METHOD__ ) {
  1265. if ( !$this->tableExists( $tableName, $fName ) ) {
  1266. return false;
  1267. }
  1268. return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
  1269. }
  1270. /**
  1271. * Get status information from SHOW STATUS in an associative array
  1272. *
  1273. * @param string $which
  1274. * @return array
  1275. */
  1276. private function getMysqlStatus( $which = "%" ) {
  1277. $flags = self::QUERY_IGNORE_DBO_TRX;
  1278. $res = $this->query( "SHOW STATUS LIKE '{$which}'", __METHOD__, $flags );
  1279. $status = [];
  1280. foreach ( $res as $row ) {
  1281. $status[$row->Variable_name] = $row->Value;
  1282. }
  1283. return $status;
  1284. }
  1285. /**
  1286. * Lists VIEWs in the database
  1287. *
  1288. * @param string|null $prefix Only show VIEWs with this prefix, eg.
  1289. * unit_test_, or $wgDBprefix. Default: null, would return all views.
  1290. * @param string $fname Name of calling function
  1291. * @return array
  1292. * @since 1.22
  1293. */
  1294. public function listViews( $prefix = null, $fname = __METHOD__ ) {
  1295. // The name of the column containing the name of the VIEW
  1296. $propertyName = 'Tables_in_' . $this->getDBname();
  1297. // Query for the VIEWS
  1298. $res = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
  1299. $allViews = [];
  1300. foreach ( $res as $row ) {
  1301. array_push( $allViews, $row->$propertyName );
  1302. }
  1303. if ( is_null( $prefix ) || $prefix === '' ) {
  1304. return $allViews;
  1305. }
  1306. $filteredViews = [];
  1307. foreach ( $allViews as $viewName ) {
  1308. // Does the name of this VIEW start with the table-prefix?
  1309. if ( strpos( $viewName, $prefix ) === 0 ) {
  1310. array_push( $filteredViews, $viewName );
  1311. }
  1312. }
  1313. return $filteredViews;
  1314. }
  1315. /**
  1316. * Differentiates between a TABLE and a VIEW.
  1317. *
  1318. * @param string $name Name of the TABLE/VIEW to test
  1319. * @param string|null $prefix
  1320. * @return bool
  1321. * @since 1.22
  1322. */
  1323. public function isView( $name, $prefix = null ) {
  1324. return in_array( $name, $this->listViews( $prefix ) );
  1325. }
  1326. protected function isTransactableQuery( $sql ) {
  1327. return parent::isTransactableQuery( $sql ) &&
  1328. !preg_match( '/^SELECT\s+(GET|RELEASE|IS_FREE)_LOCK\(/', $sql );
  1329. }
  1330. public function buildStringCast( $field ) {
  1331. return "CAST( $field AS BINARY )";
  1332. }
  1333. /**
  1334. * @param string $field Field or column to cast
  1335. * @return string
  1336. */
  1337. public function buildIntegerCast( $field ) {
  1338. return 'CAST( ' . $field . ' AS SIGNED )';
  1339. }
  1340. /*
  1341. * @return bool Whether GTID support is used (mockable for testing)
  1342. */
  1343. protected function useGTIDs() {
  1344. return $this->useGTIDs;
  1345. }
  1346. }
  1347. /**
  1348. * @deprecated since 1.29
  1349. */
  1350. class_alias( DatabaseMysqlBase::class, 'DatabaseMysqlBase' );