4 * This file deals with database interface functions
5 * and query specifics/optimisations.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 namespace Wikimedia\Rdbms
;
29 use DBUnexpectedError
;
32 * Advanced database interface for IDatabase handles that include maintenance methods
34 * This is useful for type-hints used by installer, upgrader, and background scripts
35 * that will make use of lower-level and longer-running queries, including schema changes.
40 interface IMaintainableDatabase
extends IDatabase
{
42 * Format a table name ready for use in constructing an SQL query
44 * This does two important things: it quotes the table names to clean them up,
45 * and it adds a table prefix if only given a table name with no quotes.
47 * All functions of this object which require a table name call this function
48 * themselves. Pass the canonical name to such functions. This is only needed
49 * when calling query() directly.
51 * @note This function does not sanitize user input. It is not safe to use
52 * this function to escape user input.
53 * @param string $name Database table name
54 * @param string $format One of:
55 * quoted - Automatically pass the table name through addIdentifierQuotes()
56 * so that it can be used in a query.
57 * raw - Do not add identifier quotes to the table name
58 * @return string Full database name
60 public function tableName( $name, $format = 'quoted' );
63 * Fetch a number of table names into an array
64 * This is handy when you need to construct SQL for joins
67 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
68 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
69 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
73 public function tableNames();
76 * Fetch a number of table names into an zero-indexed numerical array
77 * This is handy when you need to construct SQL for joins
80 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
81 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
82 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
86 public function tableNamesN();
89 * Returns the size of a text field, or -1 for "unlimited"
91 * @param string $table
92 * @param string $field
95 public function textFieldSize( $table, $field );
98 * Read and execute SQL commands from a file.
100 * Returns true on success, error string or exception on failure (depending
101 * on object's error ignore settings).
103 * @param string $filename File name to open
104 * @param callable|null $lineCallback Optional function called before reading each line
105 * @param callable|null $resultCallback Optional function called for each MySQL result
106 * @param bool|string $fname Calling function name or false if name should be
107 * generated dynamically using $filename
108 * @param callable|null $inputCallback Optional function called for each
110 * @return bool|string
113 public function sourceFile(
115 callable
$lineCallback = null,
116 callable
$resultCallback = null,
118 callable
$inputCallback = null
122 * Read and execute commands from an open file handle.
124 * Returns true on success, error string or exception on failure (depending
125 * on object's error ignore settings).
127 * @param resource $fp File handle
128 * @param callable|null $lineCallback Optional function called before reading each query
129 * @param callable|null $resultCallback Optional function called for each MySQL result
130 * @param string $fname Calling function name
131 * @param callable|null $inputCallback Optional function called for each complete query sent
132 * @return bool|string
134 public function sourceStream(
136 callable
$lineCallback = null,
137 callable
$resultCallback = null,
139 callable
$inputCallback = null
143 * Called by sourceStream() to check if we've reached a statement end
145 * @param string &$sql SQL assembled so far
146 * @param string &$newLine New line about to be added to $sql
147 * @return bool Whether $newLine contains end of the statement
149 public function streamStatementEnd( &$sql, &$newLine );
153 * @param string $tableName
154 * @param string $fName
155 * @return bool|ResultWrapper
157 public function dropTable( $tableName, $fName = __METHOD__
);
160 * Perform a deadlock-prone transaction.
162 * This function invokes a callback function to perform a set of write
163 * queries. If a deadlock occurs during the processing, the transaction
164 * will be rolled back and the callback function will be called again.
166 * Avoid using this method outside of Job or Maintenance classes.
169 * $dbw->deadlockLoop( callback, ... );
171 * Extra arguments are passed through to the specified callback function.
172 * This method requires that no transactions are already active to avoid
173 * causing premature commits or exceptions.
175 * Returns whatever the callback function returned on its successful,
176 * iteration, or false on error, for example if the retry limit was
180 * @throws DBUnexpectedError
183 public function deadlockLoop();
186 * Lists all the VIEWs in the database
188 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
189 * @param string $fname Name of calling function
190 * @throws RuntimeException
193 public function listViews( $prefix = null, $fname = __METHOD__
);
196 * Creates a new table with structure copied from existing table
198 * Note that unlike most database abstraction functions, this function does not
199 * automatically append database prefix, because it works at a lower abstraction level.
200 * The table names passed to this function shall not be quoted (this function calls
201 * addIdentifierQuotes() when needed).
203 * @param string $oldName Name of table whose structure should be copied
204 * @param string $newName Name of table to be created
205 * @param bool $temporary Whether the new table should be temporary
206 * @param string $fname Calling function name
207 * @return bool True if operation was successful
208 * @throws RuntimeException
210 public function duplicateTableStructure(
211 $oldName, $newName, $temporary = false, $fname = __METHOD__
215 * Checks if table locks acquired by lockTables() are transaction-bound in their scope
217 * Transaction-bound table locks will be released when the current transaction terminates.
218 * Table locks that are not bound to a transaction are not effected by BEGIN/COMMIT/ROLLBACK
219 * and will last until either lockTables()/unlockTables() is called or the TCP connection to
220 * the database is closed.
225 public function tableLocksHaveTransactionScope();
228 * Lock specific tables
230 * Any pending transaction should be resolved before calling this method, since:
231 * a) Doing so resets any REPEATABLE-READ snapshot of the data to a fresh one.
232 * b) Previous row and table locks from the transaction or session may be released
233 * by LOCK TABLES, which may be unsafe for the changes in such a transaction.
234 * c) The main use case of lockTables() is to avoid deadlocks and timeouts by locking
235 * entire tables in order to do long-running, batched, and lag-aware, updates. Batching
236 * and replication lag checks do not work when all the updates happen in a transaction.
238 * Always get all relevant table locks up-front in one call, since LOCK TABLES might release
239 * any prior table locks on some RDBMes (e.g MySQL).
241 * For compatibility, callers should check tableLocksHaveTransactionScope() before using
242 * this method. If locks are scoped specifically to transactions then caller must either:
243 * - a) Start a new transaction and acquire table locks for the scope of that transaction,
244 * doing all row updates within that transaction. It will not be possible to update
245 * rows in batches; this might result in high replication lag.
246 * - b) Forgo table locks entirely and avoid calling this method. Careful use of hints like
247 * LOCK IN SHARE MODE and FOR UPDATE and the use of query batching may be preferrable
248 * to using table locks with a potentially large transaction. Use of MySQL and Postges
249 * style REPEATABLE-READ (Snapshot Isolation with or without First-Committer-Rule) can
250 * also be considered for certain tasks that require a consistent view of entire tables.
252 * If session scoped locks are not supported, then calling lockTables() will trigger
253 * startAtomic(), with unlockTables() triggering endAtomic(). This will automatically
254 * start a transaction if one is not already present and cause the locks to be released
255 * when the transaction finishes (normally during the unlockTables() call).
257 * In any case, avoid using begin()/commit() in code that runs while such table locks are
258 * acquired, as that breaks in case when a transaction is needed. The startAtomic() and
259 * endAtomic() methods are safe, however, since they will join any existing transaction.
261 * @param array $read Array of tables to lock for read access
262 * @param array $write Array of tables to lock for write access
263 * @param string $method Name of caller
267 public function lockTables( array $read, array $write, $method );
270 * Unlock all tables locked via lockTables()
272 * If table locks are scoped to transactions, then locks might not be released until the
273 * transaction ends, which could happen after this method is called.
275 * @param string $method The caller
279 public function unlockTables( $method );
282 class_alias( 'Wikimedia\Rdbms\IMaintainableDatabase', 'IMaintainableDatabase' );