Removed old HTMLCacheUpdateJob b/c code
[lhc/web/wiklou.git] / includes / db / DatabaseMssql.php
1 <?php
2 /**
3 * This is the MS SQL Server Native database abstraction layer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 * @author Joel Penner <a-joelpe at microsoft dot com>
23 * @author Chris Pucci <a-cpucci at microsoft dot com>
24 * @author Ryan Biesemeyer <v-ryanbi at microsoft dot com>
25 * @author Ryan Schmidt <skizzerz at gmail dot com>
26 */
27
28 /**
29 * @ingroup Database
30 */
31 class DatabaseMssql extends DatabaseBase {
32 protected $mInsertId = null;
33 protected $mLastResult = null;
34 protected $mAffectedRows = null;
35 protected $mSubqueryId = 0;
36 protected $mScrollableCursor = true;
37 protected $mPrepareStatements = true;
38 protected $mBinaryColumnCache = null;
39 protected $mBitColumnCache = null;
40 protected $mIgnoreDupKeyErrors = false;
41
42 protected $mPort;
43
44 public function cascadingDeletes() {
45 return true;
46 }
47
48 public function cleanupTriggers() {
49 return false;
50 }
51
52 public function strictIPs() {
53 return false;
54 }
55
56 public function realTimestamps() {
57 return false;
58 }
59
60 public function implicitGroupby() {
61 return false;
62 }
63
64 public function implicitOrderby() {
65 return false;
66 }
67
68 public function functionalIndexes() {
69 return true;
70 }
71
72 public function unionSupportsOrderAndLimit() {
73 return false;
74 }
75
76 /**
77 * Usually aborts on failure
78 * @param string $server
79 * @param string $user
80 * @param string $password
81 * @param string $dbName
82 * @throws DBConnectionError
83 * @return bool|DatabaseBase|null
84 */
85 public function open( $server, $user, $password, $dbName ) {
86 # Test for driver support, to avoid suppressed fatal error
87 if ( !function_exists( 'sqlsrv_connect' ) ) {
88 throw new DBConnectionError(
89 $this,
90 "Microsoft SQL Server Native (sqlsrv) functions missing.
91 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
92 );
93 }
94
95 global $wgDBport, $wgDBWindowsAuthentication;
96
97 # e.g. the class is being loaded
98 if ( !strlen( $user ) ) {
99 return null;
100 }
101
102 $this->close();
103 $this->mServer = $server;
104 $this->mPort = $wgDBport;
105 $this->mUser = $user;
106 $this->mPassword = $password;
107 $this->mDBname = $dbName;
108
109 $connectionInfo = array();
110
111 if ( $dbName ) {
112 $connectionInfo['Database'] = $dbName;
113 }
114
115 // Decide which auth scenerio to use
116 // if we are using Windows auth, don't add credentials to $connectionInfo
117 if ( !$wgDBWindowsAuthentication ) {
118 $connectionInfo['UID'] = $user;
119 $connectionInfo['PWD'] = $password;
120 }
121
122 wfSuppressWarnings();
123 $this->mConn = sqlsrv_connect( $server, $connectionInfo );
124 wfRestoreWarnings();
125
126 if ( $this->mConn === false ) {
127 throw new DBConnectionError( $this, $this->lastError() );
128 }
129
130 $this->mOpened = true;
131
132 return $this->mConn;
133 }
134
135 /**
136 * Closes a database connection, if it is open
137 * Returns success, true if already closed
138 * @return bool
139 */
140 protected function closeConnection() {
141 return sqlsrv_close( $this->mConn );
142 }
143
144 /**
145 * @param bool|MssqlResultWrapper|resource $result
146 * @return bool|MssqlResultWrapper
147 */
148 public function resultObject( $result ) {
149 if ( empty( $result ) ) {
150 return false;
151 } elseif ( $result instanceof MssqlResultWrapper ) {
152 return $result;
153 } elseif ( $result === true ) {
154 // Successful write query
155 return $result;
156 } else {
157 return new MssqlResultWrapper( $this, $result );
158 }
159 }
160
161 /**
162 * @param string $sql
163 * @return bool|MssqlResult
164 * @throws DBUnexpectedError
165 */
166 protected function doQuery( $sql ) {
167 if ( $this->debug() ) {
168 wfDebug( "SQL: [$sql]\n" );
169 }
170 $this->offset = 0;
171
172 // several extensions seem to think that all databases support limits
173 // via LIMIT N after the WHERE clause well, MSSQL uses SELECT TOP N,
174 // so to catch any of those extensions we'll do a quick check for a
175 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
176 // the limit clause and passes the result to $this->limitResult();
177 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
178 // massage LIMIT -> TopN
179 $sql = $this->LimitToTopN( $sql );
180 }
181
182 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
183 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
184 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
185 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
186 }
187
188 // perform query
189
190 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
191 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
192 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
193 // strings make php throw a fatal error "Severe error translating Unicode"
194 if ( $this->mScrollableCursor ) {
195 $scrollArr = array( 'Scrollable' => SQLSRV_CURSOR_STATIC );
196 } else {
197 $scrollArr = array();
198 }
199
200 if ( $this->mPrepareStatements ) {
201 // we do prepare + execute so we can get its field metadata for later usage if desired
202 $stmt = sqlsrv_prepare( $this->mConn, $sql, array(), $scrollArr );
203 $success = sqlsrv_execute( $stmt );
204 } else {
205 $stmt = sqlsrv_query( $this->mConn, $sql, array(), $scrollArr );
206 $success = (bool)$stmt;
207 }
208
209 if ( $this->mIgnoreDupKeyErrors ) {
210 // ignore duplicate key errors, but nothing else
211 // this emulates INSERT IGNORE in MySQL
212 if ( $success === false ) {
213 $errors = sqlsrv_errors( SQLSRV_ERR_ERRORS );
214 $success = true;
215
216 foreach ( $errors as $err ) {
217 if ( $err['SQLSTATE'] == '23000' && $err['code'] == '2601' ) {
218 continue; // duplicate key error caused by unique index
219 } elseif ( $err['SQLSTATE'] == '23000' && $err['code'] == '2627' ) {
220 continue; // duplicate key error caused by primary key
221 } elseif ( $err['SQLSTATE'] == '01000' && $err['code'] == '3621' ) {
222 continue; // generic "the statement has been terminated" error
223 }
224
225 $success = false; // getting here means we got an error we weren't expecting
226 break;
227 }
228
229 if ( $success ) {
230 $this->mAffectedRows = 0;
231 return $stmt;
232 }
233 }
234 }
235
236 if ( $success === false ) {
237 return false;
238 }
239 // remember number of rows affected
240 $this->mAffectedRows = sqlsrv_rows_affected( $stmt );
241
242 return $stmt;
243 }
244
245 public function freeResult( $res ) {
246 if ( $res instanceof ResultWrapper ) {
247 $res = $res->result;
248 }
249
250 sqlsrv_free_stmt( $res );
251 }
252
253 /**
254 * @param MssqlResultWrapper $res
255 * @return stdClass
256 */
257 public function fetchObject( $res ) {
258 // $res is expected to be an instance of MssqlResultWrapper here
259 return $res->fetchObject();
260 }
261
262 /**
263 * @param MssqlResultWrapper $res
264 * @return array
265 */
266 public function fetchRow( $res ) {
267 return $res->fetchRow();
268 }
269
270 /**
271 * @param mixed $res
272 * @return int
273 */
274 public function numRows( $res ) {
275 if ( $res instanceof ResultWrapper ) {
276 $res = $res->result;
277 }
278
279 return sqlsrv_num_rows( $res );
280 }
281
282 /**
283 * @param mixed $res
284 * @return int
285 */
286 public function numFields( $res ) {
287 if ( $res instanceof ResultWrapper ) {
288 $res = $res->result;
289 }
290
291 return sqlsrv_num_fields( $res );
292 }
293
294 /**
295 * @param mixed $res
296 * @param int $n
297 * @return int
298 */
299 public function fieldName( $res, $n ) {
300 if ( $res instanceof ResultWrapper ) {
301 $res = $res->result;
302 }
303
304 $metadata = sqlsrv_field_metadata( $res );
305 return $metadata[$n]['Name'];
306 }
307
308 /**
309 * This must be called after nextSequenceVal
310 * @return int|null
311 */
312 public function insertId() {
313 return $this->mInsertId;
314 }
315
316 /**
317 * @param MssqlResultWrapper $res
318 * @param int $row
319 * @return bool
320 */
321 public function dataSeek( $res, $row ) {
322 return $res->seek( $row );
323 }
324
325 /**
326 * @return string
327 */
328 public function lastError() {
329 $strRet = '';
330 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL );
331 if ( $retErrors != null ) {
332 foreach ( $retErrors as $arrError ) {
333 $strRet .= $this->formatError( $arrError ) . "\n";
334 }
335 } else {
336 $strRet = "No errors found";
337 }
338
339 return $strRet;
340 }
341
342 /**
343 * @param array $err
344 * @return string
345 */
346 private function formatError( $err ) {
347 return '[SQLSTATE ' . $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
348 }
349
350 /**
351 * @return string
352 */
353 public function lastErrno() {
354 $err = sqlsrv_errors( SQLSRV_ERR_ALL );
355 if ( $err !== null && isset( $err[0] ) ) {
356 return $err[0]['code'];
357 } else {
358 return 0;
359 }
360 }
361
362 /**
363 * @return int
364 */
365 public function affectedRows() {
366 return $this->mAffectedRows;
367 }
368
369 /**
370 * SELECT wrapper
371 *
372 * @param mixed $table Array or string, table name(s) (prefix auto-added)
373 * @param mixed $vars Array or string, field name(s) to be retrieved
374 * @param mixed $conds Array or string, condition(s) for WHERE
375 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
376 * @param array $options Associative array of options (e.g.
377 * array('GROUP BY' => 'page_title')), see Database::makeSelectOptions
378 * code for list of supported stuff
379 * @param array $join_conds Associative array of table join conditions
380 * (optional) (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
381 * @return mixed Database result resource (feed to Database::fetchObject
382 * or whatever), or false on failure
383 * @throws DBQueryError
384 * @throws DBUnexpectedError
385 * @throws Exception
386 */
387 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
388 $options = array(), $join_conds = array()
389 ) {
390 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
391 if ( isset( $options['EXPLAIN'] ) ) {
392 try {
393 $this->mScrollableCursor = false;
394 $this->mPrepareStatements = false;
395 $this->query( "SET SHOWPLAN_ALL ON" );
396 $ret = $this->query( $sql, $fname );
397 $this->query( "SET SHOWPLAN_ALL OFF" );
398 } catch ( DBQueryError $dqe ) {
399 if ( isset( $options['FOR COUNT'] ) ) {
400 // likely don't have privs for SHOWPLAN, so run a select count instead
401 $this->query( "SET SHOWPLAN_ALL OFF" );
402 unset( $options['EXPLAIN'] );
403 $ret = $this->select(
404 $table,
405 'COUNT(*) AS EstimateRows',
406 $conds,
407 $fname,
408 $options,
409 $join_conds
410 );
411 } else {
412 // someone actually wanted the query plan instead of an est row count
413 // let them know of the error
414 $this->mScrollableCursor = true;
415 $this->mPrepareStatements = true;
416 throw $dqe;
417 }
418 }
419 $this->mScrollableCursor = true;
420 $this->mPrepareStatements = true;
421 return $ret;
422 }
423 return $this->query( $sql, $fname );
424 }
425
426 /**
427 * SELECT wrapper
428 *
429 * @param mixed $table Array or string, table name(s) (prefix auto-added)
430 * @param mixed $vars Array or string, field name(s) to be retrieved
431 * @param mixed $conds Array or string, condition(s) for WHERE
432 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
433 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
434 * see Database::makeSelectOptions code for list of supported stuff
435 * @param array $join_conds Associative array of table join conditions (optional)
436 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
437 * @return string The SQL text
438 */
439 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
440 $options = array(), $join_conds = array()
441 ) {
442 if ( isset( $options['EXPLAIN'] ) ) {
443 unset( $options['EXPLAIN'] );
444 }
445
446 $sql = parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
447
448 // try to rewrite aggregations of bit columns (currently MAX and MIN)
449 if ( strpos( $sql, 'MAX(' ) !== false || strpos( $sql, 'MIN(' ) !== false ) {
450 $bitColumns = array();
451 if ( is_array( $table ) ) {
452 foreach ( $table as $t ) {
453 $bitColumns += $this->getBitColumns( $this->tableName( $t ) );
454 }
455 } else {
456 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
457 }
458
459 foreach ( $bitColumns as $col => $info ) {
460 $replace = array(
461 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
462 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
463 );
464 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
465 }
466 }
467
468 return $sql;
469 }
470
471 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
472 $fname = __METHOD__
473 ) {
474 $this->mScrollableCursor = false;
475 try {
476 parent::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
477 } catch ( Exception $e ) {
478 $this->mScrollableCursor = true;
479 throw $e;
480 }
481 $this->mScrollableCursor = true;
482 }
483
484 public function delete( $table, $conds, $fname = __METHOD__ ) {
485 $this->mScrollableCursor = false;
486 try {
487 parent::delete( $table, $conds, $fname );
488 } catch ( Exception $e ) {
489 $this->mScrollableCursor = true;
490 throw $e;
491 }
492 $this->mScrollableCursor = true;
493 }
494
495 /**
496 * Estimate rows in dataset
497 * Returns estimated count, based on SHOWPLAN_ALL output
498 * This is not necessarily an accurate estimate, so use sparingly
499 * Returns -1 if count cannot be found
500 * Takes same arguments as Database::select()
501 * @param string $table
502 * @param string $vars
503 * @param string $conds
504 * @param string $fname
505 * @param array $options
506 * @return int
507 */
508 public function estimateRowCount( $table, $vars = '*', $conds = '',
509 $fname = __METHOD__, $options = array()
510 ) {
511 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
512 $options['EXPLAIN'] = true;
513 $options['FOR COUNT'] = true;
514 $res = $this->select( $table, $vars, $conds, $fname, $options );
515
516 $rows = -1;
517 if ( $res ) {
518 $row = $this->fetchRow( $res );
519
520 if ( isset( $row['EstimateRows'] ) ) {
521 $rows = (int)$row['EstimateRows'];
522 }
523 }
524
525 return $rows;
526 }
527
528 /**
529 * Returns information about an index
530 * If errors are explicitly ignored, returns NULL on failure
531 * @param string $table
532 * @param string $index
533 * @param string $fname
534 * @return array|bool|null
535 */
536 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
537 # This does not return the same info as MYSQL would, but that's OK
538 # because MediaWiki never uses the returned value except to check for
539 # the existance of indexes.
540 $sql = "sp_helpindex '" . $table . "'";
541 $res = $this->query( $sql, $fname );
542 if ( !$res ) {
543 return null;
544 }
545
546 $result = array();
547 foreach ( $res as $row ) {
548 if ( $row->index_name == $index ) {
549 $row->Non_unique = !stristr( $row->index_description, "unique" );
550 $cols = explode( ", ", $row->index_keys );
551 foreach ( $cols as $col ) {
552 $row->Column_name = trim( $col );
553 $result[] = clone $row;
554 }
555 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description, 'PRIMARY' ) ) {
556 $row->Non_unique = 0;
557 $cols = explode( ", ", $row->index_keys );
558 foreach ( $cols as $col ) {
559 $row->Column_name = trim( $col );
560 $result[] = clone $row;
561 }
562 }
563 }
564
565 return empty( $result ) ? false : $result;
566 }
567
568 /**
569 * INSERT wrapper, inserts an array into a table
570 *
571 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
572 * multi-row insert.
573 *
574 * Usually aborts on failure
575 * If errors are explicitly ignored, returns success
576 * @param string $table
577 * @param array $arrToInsert
578 * @param string $fname
579 * @param array $options
580 * @return bool
581 * @throws Exception
582 */
583 public function insert( $table, $arrToInsert, $fname = __METHOD__, $options = array() ) {
584 # No rows to insert, easy just return now
585 if ( !count( $arrToInsert ) ) {
586 return true;
587 }
588
589 if ( !is_array( $options ) ) {
590 $options = array( $options );
591 }
592
593 $table = $this->tableName( $table );
594
595 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
596 $arrToInsert = array( 0 => $arrToInsert ); // make everything multi row compatible
597 }
598
599 // We know the table we're inserting into, get its identity column
600 $identity = null;
601 // strip matching square brackets and the db/schema from table name
602 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
603 $tableRaw = array_pop( $tableRawArr );
604 $res = $this->doQuery(
605 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
606 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
607 );
608 if ( $res && sqlsrv_has_rows( $res ) ) {
609 // There is an identity for this table.
610 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC );
611 $identity = array_pop( $identityArr );
612 }
613 sqlsrv_free_stmt( $res );
614
615 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
616 $binaryColumns = $this->getBinaryColumns( $table );
617
618 // INSERT IGNORE is not supported by SQL Server
619 // remove IGNORE from options list and set ignore flag to true
620 if ( in_array( 'IGNORE', $options ) ) {
621 $options = array_diff( $options, array( 'IGNORE' ) );
622 $this->mIgnoreDupKeyErrors = true;
623 }
624
625 foreach ( $arrToInsert as $a ) {
626 // start out with empty identity column, this is so we can return
627 // it as a result of the insert logic
628 $sqlPre = '';
629 $sqlPost = '';
630 $identityClause = '';
631
632 // if we have an identity column
633 if ( $identity ) {
634 // iterate through
635 foreach ( $a as $k => $v ) {
636 if ( $k == $identity ) {
637 if ( !is_null( $v ) ) {
638 // there is a value being passed to us,
639 // we need to turn on and off inserted identity
640 $sqlPre = "SET IDENTITY_INSERT $table ON;";
641 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
642 } else {
643 // we can't insert NULL into an identity column,
644 // so remove the column from the insert.
645 unset( $a[$k] );
646 }
647 }
648 }
649
650 // we want to output an identity column as result
651 $identityClause = "OUTPUT INSERTED.$identity ";
652 }
653
654 $keys = array_keys( $a );
655
656 // Build the actual query
657 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
658 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
659
660 $first = true;
661 foreach ( $a as $key => $value ) {
662 if ( isset( $binaryColumns[$key] ) ) {
663 $value = new MssqlBlob( $value );
664 }
665 if ( $first ) {
666 $first = false;
667 } else {
668 $sql .= ',';
669 }
670 if ( is_null( $value ) ) {
671 $sql .= 'null';
672 } elseif ( is_array( $value ) || is_object( $value ) ) {
673 if ( is_object( $value ) && $value instanceof Blob ) {
674 $sql .= $this->addQuotes( $value );
675 } else {
676 $sql .= $this->addQuotes( serialize( $value ) );
677 }
678 } else {
679 $sql .= $this->addQuotes( $value );
680 }
681 }
682 $sql .= ')' . $sqlPost;
683
684 // Run the query
685 $this->mScrollableCursor = false;
686 try {
687 $ret = $this->query( $sql );
688 } catch ( Exception $e ) {
689 $this->mScrollableCursor = true;
690 $this->mIgnoreDupKeyErrors = false;
691 throw $e;
692 }
693 $this->mScrollableCursor = true;
694
695 if ( !is_null( $identity ) ) {
696 // then we want to get the identity column value we were assigned and save it off
697 $row = $ret->fetchObject();
698 if ( is_object( $row ) ) {
699 $this->mInsertId = $row->$identity;
700 }
701 }
702 }
703 $this->mIgnoreDupKeyErrors = false;
704 return $ret;
705 }
706
707 /**
708 * INSERT SELECT wrapper
709 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
710 * Source items may be literals rather than field names, but strings should
711 * be quoted with Database::addQuotes().
712 * @param string $destTable
713 * @param array|string $srcTable May be an array of tables.
714 * @param array $varMap
715 * @param array $conds May be "*" to copy the whole table.
716 * @param string $fname
717 * @param array $insertOptions
718 * @param array $selectOptions
719 * @return null|ResultWrapper
720 * @throws Exception
721 */
722 public function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
723 $insertOptions = array(), $selectOptions = array()
724 ) {
725 $this->mScrollableCursor = false;
726 try {
727 $ret = parent::insertSelect(
728 $destTable,
729 $srcTable,
730 $varMap,
731 $conds,
732 $fname,
733 $insertOptions,
734 $selectOptions
735 );
736 } catch ( Exception $e ) {
737 $this->mScrollableCursor = true;
738 throw $e;
739 }
740 $this->mScrollableCursor = true;
741
742 return $ret;
743 }
744
745 /**
746 * UPDATE wrapper. Takes a condition array and a SET array.
747 *
748 * @param string $table Name of the table to UPDATE. This will be passed through
749 * DatabaseBase::tableName().
750 *
751 * @param array $values An array of values to SET. For each array element,
752 * the key gives the field name, and the value gives the data
753 * to set that field to. The data will be quoted by
754 * DatabaseBase::addQuotes().
755 *
756 * @param array $conds An array of conditions (WHERE). See
757 * DatabaseBase::select() for the details of the format of
758 * condition arrays. Use '*' to update all rows.
759 *
760 * @param string $fname The function name of the caller (from __METHOD__),
761 * for logging and profiling.
762 *
763 * @param array $options An array of UPDATE options, can be:
764 * - IGNORE: Ignore unique key conflicts
765 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
766 * @return bool
767 * @throws DBUnexpectedError
768 * @throws Exception
769 * @throws MWException
770 */
771 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
772 $table = $this->tableName( $table );
773 $binaryColumns = $this->getBinaryColumns( $table );
774
775 $opts = $this->makeUpdateOptions( $options );
776 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET, $binaryColumns );
777
778 if ( $conds !== array() && $conds !== '*' ) {
779 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND, $binaryColumns );
780 }
781
782 $this->mScrollableCursor = false;
783 try {
784 $ret = $this->query( $sql );
785 } catch ( Exception $e ) {
786 $this->mScrollableCursor = true;
787 throw $e;
788 }
789 $this->mScrollableCursor = true;
790 return true;
791 }
792
793 /**
794 * Makes an encoded list of strings from an array
795 * @param array $a Containing the data
796 * @param int $mode Constant
797 * - LIST_COMMA: comma separated, no field names
798 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
799 * the documentation for $conds in DatabaseBase::select().
800 * - LIST_OR: ORed WHERE clause (without the WHERE)
801 * - LIST_SET: comma separated with field names, like a SET clause
802 * - LIST_NAMES: comma separated field names
803 * @param array $binaryColumns Contains a list of column names that are binary types
804 * This is a custom parameter only present for MS SQL.
805 *
806 * @throws MWException|DBUnexpectedError
807 * @return string
808 */
809 public function makeList( $a, $mode = LIST_COMMA, $binaryColumns = array() ) {
810 if ( !is_array( $a ) ) {
811 throw new DBUnexpectedError( $this,
812 'DatabaseBase::makeList called with incorrect parameters' );
813 }
814
815 $first = true;
816 $list = '';
817
818 foreach ( $a as $field => $value ) {
819 if ( $mode != LIST_NAMES && isset( $binaryColumns[$field] ) ) {
820 if ( is_array( $value ) ) {
821 foreach ( $value as &$v ) {
822 $v = new MssqlBlob( $v );
823 }
824 } else {
825 $value = new MssqlBlob( $value );
826 }
827 }
828
829 if ( !$first ) {
830 if ( $mode == LIST_AND ) {
831 $list .= ' AND ';
832 } elseif ( $mode == LIST_OR ) {
833 $list .= ' OR ';
834 } else {
835 $list .= ',';
836 }
837 } else {
838 $first = false;
839 }
840
841 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
842 $list .= "($value)";
843 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
844 $list .= "$value";
845 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
846 if ( count( $value ) == 0 ) {
847 throw new MWException( __METHOD__ . ": empty input for field $field" );
848 } elseif ( count( $value ) == 1 ) {
849 // Special-case single values, as IN isn't terribly efficient
850 // Don't necessarily assume the single key is 0; we don't
851 // enforce linear numeric ordering on other arrays here.
852 $value = array_values( $value );
853 $list .= $field . " = " . $this->addQuotes( $value[0] );
854 } else {
855 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
856 }
857 } elseif ( $value === null ) {
858 if ( $mode == LIST_AND || $mode == LIST_OR ) {
859 $list .= "$field IS ";
860 } elseif ( $mode == LIST_SET ) {
861 $list .= "$field = ";
862 }
863 $list .= 'NULL';
864 } else {
865 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
866 $list .= "$field = ";
867 }
868 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
869 }
870 }
871
872 return $list;
873 }
874
875 /**
876 * @param string $table
877 * @param string $field
878 * @return int Returns the size of a text field, or -1 for "unlimited"
879 */
880 public function textFieldSize( $table, $field ) {
881 $table = $this->tableName( $table );
882 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
883 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
884 $res = $this->query( $sql );
885 $row = $this->fetchRow( $res );
886 $size = -1;
887 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
888 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
889 }
890
891 return $size;
892 }
893
894 /**
895 * Construct a LIMIT query with optional offset
896 * This is used for query pages
897 *
898 * @param string $sql SQL query we will append the limit too
899 * @param int $limit The SQL limit
900 * @param bool|int $offset The SQL offset (default false)
901 * @return array|string
902 * @throws DBUnexpectedError
903 */
904 public function limitResult( $sql, $limit, $offset = false ) {
905 if ( $offset === false || $offset == 0 ) {
906 if ( strpos( $sql, "SELECT" ) === false ) {
907 return "TOP {$limit} " . $sql;
908 } else {
909 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
910 'SELECT$1 TOP ' . $limit, $sql, 1 );
911 }
912 } else {
913 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
914 $select = $orderby = array();
915 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
916 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
917 $overOrder = $postOrder = '';
918 $first = $offset + 1;
919 $last = $offset + $limit;
920 $sub1 = 'sub_' . $this->mSubqueryId;
921 $sub2 = 'sub_' . ( $this->mSubqueryId + 1 );
922 $this->mSubqueryId += 2;
923 if ( !$s1 ) {
924 // wat
925 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
926 }
927 if ( !$s2 ) {
928 // no ORDER BY
929 $overOrder = 'ORDER BY (SELECT 1)';
930 } else {
931 if ( !isset( $orderby[2] ) || !$orderby[2] ) {
932 // don't need to strip it out if we're using a FOR XML clause
933 $sql = str_replace( $orderby[1], '', $sql );
934 }
935 $overOrder = $orderby[1];
936 $postOrder = ' ' . $overOrder;
937 }
938 $sql = "SELECT {$select[1]}
939 FROM (
940 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
941 FROM ({$sql}) {$sub1}
942 ) {$sub2}
943 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
944
945 return $sql;
946 }
947 }
948
949 /**
950 * If there is a limit clause, parse it, strip it, and pass the remaining
951 * SQL through limitResult() with the appropriate parameters. Not the
952 * prettiest solution, but better than building a whole new parser. This
953 * exists becase there are still too many extensions that don't use dynamic
954 * sql generation.
955 *
956 * @param string $sql
957 * @return array|mixed|string
958 */
959 public function LimitToTopN( $sql ) {
960 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
961 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
962 if ( preg_match( $pattern, $sql, $matches ) ) {
963 $row_count = $matches[4];
964 $offset = $matches[3] ?: $matches[6] ?: false;
965
966 // strip the matching LIMIT clause out
967 $sql = str_replace( $matches[0], '', $sql );
968
969 return $this->limitResult( $sql, $row_count, $offset );
970 }
971
972 return $sql;
973 }
974
975 /**
976 * @return string Wikitext of a link to the server software's web site
977 */
978 public function getSoftwareLink() {
979 return "[{{int:version-db-mssql-url}} MS SQL Server]";
980 }
981
982 /**
983 * @return string Version information from the database
984 */
985 public function getServerVersion() {
986 $server_info = sqlsrv_server_info( $this->mConn );
987 $version = 'Error';
988 if ( isset( $server_info['SQLServerVersion'] ) ) {
989 $version = $server_info['SQLServerVersion'];
990 }
991
992 return $version;
993 }
994
995 /**
996 * @param string $table
997 * @param string $fname
998 * @return bool
999 */
1000 public function tableExists( $table, $fname = __METHOD__ ) {
1001 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1002
1003 if ( $db !== false ) {
1004 // remote database
1005 wfDebug( "Attempting to call tableExists on a remote table" );
1006 return false;
1007 }
1008
1009 if ( $schema === false ) {
1010 global $wgDBmwschema;
1011 $schema = $wgDBmwschema;
1012 }
1013
1014 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1015 WHERE TABLE_TYPE = 'BASE TABLE'
1016 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1017
1018 if ( $res->numRows() ) {
1019 return true;
1020 } else {
1021 return false;
1022 }
1023 }
1024
1025 /**
1026 * Query whether a given column exists in the mediawiki schema
1027 * @param string $table
1028 * @param string $field
1029 * @param string $fname
1030 * @return bool
1031 */
1032 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1033 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1034
1035 if ( $db !== false ) {
1036 // remote database
1037 wfDebug( "Attempting to call fieldExists on a remote table" );
1038 return false;
1039 }
1040
1041 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1042 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1043
1044 if ( $res->numRows() ) {
1045 return true;
1046 } else {
1047 return false;
1048 }
1049 }
1050
1051 public function fieldInfo( $table, $field ) {
1052 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1053
1054 if ( $db !== false ) {
1055 // remote database
1056 wfDebug( "Attempting to call fieldInfo on a remote table" );
1057 return false;
1058 }
1059
1060 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1061 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1062
1063 $meta = $res->fetchRow();
1064 if ( $meta ) {
1065 return new MssqlField( $meta );
1066 }
1067
1068 return false;
1069 }
1070
1071 /**
1072 * Begin a transaction, committing any previously open transaction
1073 * @param string $fname
1074 */
1075 protected function doBegin( $fname = __METHOD__ ) {
1076 sqlsrv_begin_transaction( $this->mConn );
1077 $this->mTrxLevel = 1;
1078 }
1079
1080 /**
1081 * End a transaction
1082 * @param string $fname
1083 */
1084 protected function doCommit( $fname = __METHOD__ ) {
1085 sqlsrv_commit( $this->mConn );
1086 $this->mTrxLevel = 0;
1087 }
1088
1089 /**
1090 * Rollback a transaction.
1091 * No-op on non-transactional databases.
1092 * @param string $fname
1093 */
1094 protected function doRollback( $fname = __METHOD__ ) {
1095 sqlsrv_rollback( $this->mConn );
1096 $this->mTrxLevel = 0;
1097 }
1098
1099 /**
1100 * Escapes a identifier for use inm SQL.
1101 * Throws an exception if it is invalid.
1102 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
1103 * @param string $identifier
1104 * @throws MWException
1105 * @return string
1106 */
1107 private function escapeIdentifier( $identifier ) {
1108 if ( strlen( $identifier ) == 0 ) {
1109 throw new MWException( "An identifier must not be empty" );
1110 }
1111 if ( strlen( $identifier ) > 128 ) {
1112 throw new MWException( "The identifier '$identifier' is too long (max. 128)" );
1113 }
1114 if ( ( strpos( $identifier, '[' ) !== false )
1115 || ( strpos( $identifier, ']' ) !== false )
1116 ) {
1117 // It may be allowed if you quoted with double quotation marks, but
1118 // that would break if QUOTED_IDENTIFIER is OFF
1119 throw new MWException( "Square brackets are not allowed in '$identifier'" );
1120 }
1121
1122 return "[$identifier]";
1123 }
1124
1125 /**
1126 * @param string $s
1127 * @return string
1128 */
1129 public function strencode( $s ) { # Should not be called by us
1130 return str_replace( "'", "''", $s );
1131 }
1132
1133 /**
1134 * @param string $s
1135 * @return string
1136 */
1137 public function addQuotes( $s ) {
1138 if ( $s instanceof MssqlBlob ) {
1139 return $s->fetch();
1140 } elseif ( $s instanceof Blob ) {
1141 // this shouldn't really ever be called, but it's here if needed
1142 // (and will quite possibly make the SQL error out)
1143 $blob = new MssqlBlob( $s->fetch() );
1144 return $blob->fetch();
1145 } else {
1146 if ( is_bool( $s ) ) {
1147 $s = $s ? 1 : 0;
1148 }
1149 return parent::addQuotes( $s );
1150 }
1151 }
1152
1153 /**
1154 * @param string $s
1155 * @return string
1156 */
1157 public function addIdentifierQuotes( $s ) {
1158 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1159 return '[' . $s . ']';
1160 }
1161
1162 /**
1163 * @param string $name
1164 * @return bool
1165 */
1166 public function isQuotedIdentifier( $name ) {
1167 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1168 }
1169
1170 /**
1171 * @param string $db
1172 * @return bool
1173 */
1174 public function selectDB( $db ) {
1175 try {
1176 $this->mDBname = $db;
1177 $this->query( "USE $db" );
1178 return true;
1179 } catch ( Exception $e ) {
1180 return false;
1181 }
1182 }
1183
1184 /**
1185 * @param array $options An associative array of options to be turned into
1186 * an SQL query, valid keys are listed in the function.
1187 * @return array
1188 */
1189 public function makeSelectOptions( $options ) {
1190 $tailOpts = '';
1191 $startOpts = '';
1192
1193 $noKeyOptions = array();
1194 foreach ( $options as $key => $option ) {
1195 if ( is_numeric( $key ) ) {
1196 $noKeyOptions[$option] = true;
1197 }
1198 }
1199
1200 $tailOpts .= $this->makeGroupByWithHaving( $options );
1201
1202 $tailOpts .= $this->makeOrderBy( $options );
1203
1204 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1205 $startOpts .= 'DISTINCT';
1206 }
1207
1208 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1209 // used in group concat field emulation
1210 $tailOpts .= " FOR XML PATH('')";
1211 }
1212
1213 // we want this to be compatible with the output of parent::makeSelectOptions()
1214 return array( $startOpts, '', $tailOpts, '' );
1215 }
1216
1217 /**
1218 * Get the type of the DBMS, as it appears in $wgDBtype.
1219 * @return string
1220 */
1221 public function getType() {
1222 return 'mssql';
1223 }
1224
1225 /**
1226 * @param array $stringList
1227 * @return string
1228 */
1229 public function buildConcat( $stringList ) {
1230 return implode( ' + ', $stringList );
1231 }
1232
1233 /**
1234 * Build a GROUP_CONCAT or equivalent statement for a query.
1235 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1236 *
1237 * This is useful for combining a field for several rows into a single string.
1238 * NULL values will not appear in the output, duplicated values will appear,
1239 * and the resulting delimiter-separated values have no defined sort order.
1240 * Code using the results may need to use the PHP unique() or sort() methods.
1241 *
1242 * @param string $delim Glue to bind the results together
1243 * @param string|array $table Table name
1244 * @param string $field Field name
1245 * @param string|array $conds Conditions
1246 * @param string|array $join_conds Join conditions
1247 * @return string SQL text
1248 * @since 1.23
1249 */
1250 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1251 $join_conds = array()
1252 ) {
1253 $gcsq = 'gcsq_' . $this->mSubqueryId;
1254 $this->mSubqueryId++;
1255
1256 $delimLen = strlen( $delim );
1257 $fld = "{$field} + {$this->addQuotes( $delim )}";
1258 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1259 . $this->selectSQLText( $table, $fld, $conds, null, array( 'FOR XML' ), $join_conds )
1260 . ") {$gcsq} ({$field}))";
1261
1262 return $sql;
1263 }
1264
1265 /**
1266 * @return string
1267 */
1268 public function getSearchEngine() {
1269 return "SearchMssql";
1270 }
1271
1272 /**
1273 * Returns an associative array for fields that are of type varbinary, binary, or image
1274 * $table can be either a raw table name or passed through tableName() first
1275 * @param string $table
1276 * @return array
1277 */
1278 private function getBinaryColumns( $table ) {
1279 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1280 $tableRaw = array_pop( $tableRawArr );
1281
1282 if ( $this->mBinaryColumnCache === null ) {
1283 $this->populateColumnCaches();
1284 }
1285
1286 return isset( $this->mBinaryColumnCache[$tableRaw] )
1287 ? $this->mBinaryColumnCache[$tableRaw]
1288 : array();
1289 }
1290
1291 /**
1292 * @param string $table
1293 * @return array
1294 */
1295 private function getBitColumns( $table ) {
1296 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1297 $tableRaw = array_pop( $tableRawArr );
1298
1299 if ( $this->mBitColumnCache === null ) {
1300 $this->populateColumnCaches();
1301 }
1302
1303 return isset( $this->mBitColumnCache[$tableRaw] )
1304 ? $this->mBitColumnCache[$tableRaw]
1305 : array();
1306 }
1307
1308 private function populateColumnCaches() {
1309 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1310 array(
1311 'TABLE_CATALOG' => $this->mDBname,
1312 'TABLE_SCHEMA' => $this->mSchema,
1313 'DATA_TYPE' => array( 'varbinary', 'binary', 'image', 'bit' )
1314 ) );
1315
1316 $this->mBinaryColumnCache = array();
1317 $this->mBitColumnCache = array();
1318 foreach ( $res as $row ) {
1319 if ( $row->DATA_TYPE == 'bit' ) {
1320 $this->mBitColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1321 } else {
1322 $this->mBinaryColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1323 }
1324 }
1325 }
1326
1327 /**
1328 * @param string $name
1329 * @param string $format
1330 * @return string
1331 */
1332 function tableName( $name, $format = 'quoted' ) {
1333 # Replace reserved words with better ones
1334 switch ( $name ) {
1335 case 'user':
1336 return $this->realTableName( 'mwuser', $format );
1337 default:
1338 return $this->realTableName( $name, $format );
1339 }
1340 }
1341
1342 /**
1343 * call this instead of tableName() in the updater when renaming tables
1344 * @param string $name
1345 * @param string $format One of quoted, raw, or split
1346 * @return string
1347 */
1348 function realTableName( $name, $format = 'quoted' ) {
1349 $table = parent::tableName( $name, $format );
1350 if ( $format == 'split' ) {
1351 // Used internally, we want the schema split off from the table name and returned
1352 // as a list with 3 elements (database, schema, table)
1353 $table = explode( '.', $table );
1354 while ( count( $table ) < 3 ) {
1355 array_unshift( $table, false );
1356 }
1357 }
1358 return $table;
1359 }
1360
1361 /**
1362 * Called in the installer and updater.
1363 * Probably doesn't need to be called anywhere else in the codebase.
1364 * @param bool|null $value
1365 * @return bool|null
1366 */
1367 public function prepareStatements( $value = null ) {
1368 return wfSetVar( $this->mPrepareStatements, $value );
1369 }
1370
1371 /**
1372 * Called in the installer and updater.
1373 * Probably doesn't need to be called anywhere else in the codebase.
1374 * @param bool|null $value
1375 * @return bool|null
1376 */
1377 public function scrollableCursor( $value = null ) {
1378 return wfSetVar( $this->mScrollableCursor, $value );
1379 }
1380 } // end DatabaseMssql class
1381
1382 /**
1383 * Utility class.
1384 *
1385 * @ingroup Database
1386 */
1387 class MssqlField implements Field {
1388 private $name, $tableName, $default, $max_length, $nullable, $type;
1389
1390 function __construct( $info ) {
1391 $this->name = $info['COLUMN_NAME'];
1392 $this->tableName = $info['TABLE_NAME'];
1393 $this->default = $info['COLUMN_DEFAULT'];
1394 $this->max_length = $info['CHARACTER_MAXIMUM_LENGTH'];
1395 $this->nullable = !( strtolower( $info['IS_NULLABLE'] ) == 'no' );
1396 $this->type = $info['DATA_TYPE'];
1397 }
1398
1399 function name() {
1400 return $this->name;
1401 }
1402
1403 function tableName() {
1404 return $this->tableName;
1405 }
1406
1407 function defaultValue() {
1408 return $this->default;
1409 }
1410
1411 function maxLength() {
1412 return $this->max_length;
1413 }
1414
1415 function isNullable() {
1416 return $this->nullable;
1417 }
1418
1419 function type() {
1420 return $this->type;
1421 }
1422 }
1423
1424 class MssqlBlob extends Blob {
1425 public function __construct( $data ) {
1426 if ( $data instanceof MssqlBlob ) {
1427 return $data;
1428 } elseif ( $data instanceof Blob ) {
1429 $this->mData = $data->fetch();
1430 } elseif ( is_array( $data ) && is_object( $data ) ) {
1431 $this->mData = serialize( $data );
1432 } else {
1433 $this->mData = $data;
1434 }
1435 }
1436
1437 /**
1438 * Returns an unquoted hex representation of a binary string
1439 * for insertion into varbinary-type fields
1440 * @return string
1441 */
1442 public function fetch() {
1443 if ( $this->mData === null ) {
1444 return 'null';
1445 }
1446
1447 $ret = '0x';
1448 $dataLength = strlen( $this->mData );
1449 for ( $i = 0; $i < $dataLength; $i++ ) {
1450 $ret .= bin2hex( pack( 'C', ord( $this->mData[$i] ) ) );
1451 }
1452
1453 return $ret;
1454 }
1455 }
1456
1457 class MssqlResultWrapper extends ResultWrapper {
1458 private $mSeekTo = null;
1459
1460 /**
1461 * @return stdClass|bool
1462 */
1463 public function fetchObject() {
1464 $res = $this->result;
1465
1466 if ( $this->mSeekTo !== null ) {
1467 $result = sqlsrv_fetch_object( $res, 'stdClass', array(),
1468 SQLSRV_SCROLL_ABSOLUTE, $this->mSeekTo );
1469 $this->mSeekTo = null;
1470 } else {
1471 $result = sqlsrv_fetch_object( $res );
1472 }
1473
1474 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1475 if ( $result === null ) {
1476 return false;
1477 }
1478
1479 return $result;
1480 }
1481
1482 /**
1483 * @return array|bool
1484 */
1485 public function fetchRow() {
1486 $res = $this->result;
1487
1488 if ( $this->mSeekTo !== null ) {
1489 $result = sqlsrv_fetch_array( $res, SQLSRV_FETCH_BOTH,
1490 SQLSRV_SCROLL_ABSOLUTE, $this->mSeekTo );
1491 $this->mSeekTo = null;
1492 } else {
1493 $result = sqlsrv_fetch_array( $res );
1494 }
1495
1496 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1497 if ( $result === null ) {
1498 return false;
1499 }
1500
1501 return $result;
1502 }
1503
1504 /**
1505 * @param int $row
1506 * @return bool
1507 */
1508 public function seek( $row ) {
1509 $res = $this->result;
1510
1511 // check bounds
1512 $numRows = $this->db->numRows( $res );
1513 $row = intval( $row );
1514
1515 if ( $numRows === 0 ) {
1516 return false;
1517 } elseif ( $row < 0 || $row > $numRows - 1 ) {
1518 return false;
1519 }
1520
1521 // Unlike MySQL, the seek actually happens on the next access
1522 $this->mSeekTo = $row;
1523 return true;
1524 }
1525 }