IDatabase.php 80 KB

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