Merge "Using ULS in Special:PageLanguage"
[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 true;
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 */
384 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
385 $options = array(), $join_conds = array()
386 ) {
387 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
388 if ( isset( $options['EXPLAIN'] ) ) {
389 try {
390 $this->mScrollableCursor = false;
391 $this->mPrepareStatements = false;
392 $this->query( "SET SHOWPLAN_ALL ON" );
393 $ret = $this->query( $sql, $fname );
394 $this->query( "SET SHOWPLAN_ALL OFF" );
395 } catch ( DBQueryError $dqe ) {
396 if ( isset( $options['FOR COUNT'] ) ) {
397 // likely don't have privs for SHOWPLAN, so run a select count instead
398 $this->query( "SET SHOWPLAN_ALL OFF" );
399 unset( $options['EXPLAIN'] );
400 $ret = $this->select(
401 $table,
402 'COUNT(*) AS EstimateRows',
403 $conds,
404 $fname,
405 $options,
406 $join_conds
407 );
408 } else {
409 // someone actually wanted the query plan instead of an est row count
410 // let them know of the error
411 $this->mScrollableCursor = true;
412 $this->mPrepareStatements = true;
413 throw $dqe;
414 }
415 }
416 $this->mScrollableCursor = true;
417 $this->mPrepareStatements = true;
418
419 return $ret;
420 }
421
422 return $this->query( $sql, $fname );
423 }
424
425 /**
426 * SELECT wrapper
427 *
428 * @param mixed $table Array or string, table name(s) (prefix auto-added)
429 * @param mixed $vars Array or string, field name(s) to be retrieved
430 * @param mixed $conds Array or string, condition(s) for WHERE
431 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
432 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
433 * see Database::makeSelectOptions code for list of supported stuff
434 * @param array $join_conds Associative array of table join conditions (optional)
435 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
436 * @return string The SQL text
437 */
438 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
439 $options = array(), $join_conds = array()
440 ) {
441 if ( isset( $options['EXPLAIN'] ) ) {
442 unset( $options['EXPLAIN'] );
443 }
444
445 $sql = parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
446
447 // try to rewrite aggregations of bit columns (currently MAX and MIN)
448 if ( strpos( $sql, 'MAX(' ) !== false || strpos( $sql, 'MIN(' ) !== false ) {
449 $bitColumns = array();
450 if ( is_array( $table ) ) {
451 foreach ( $table as $t ) {
452 $bitColumns += $this->getBitColumns( $this->tableName( $t ) );
453 }
454 } else {
455 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
456 }
457
458 foreach ( $bitColumns as $col => $info ) {
459 $replace = array(
460 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
461 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
462 );
463 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
464 }
465 }
466
467 return $sql;
468 }
469
470 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
471 $fname = __METHOD__
472 ) {
473 $this->mScrollableCursor = false;
474 try {
475 parent::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
476 } catch ( Exception $e ) {
477 $this->mScrollableCursor = true;
478 throw $e;
479 }
480 $this->mScrollableCursor = true;
481 }
482
483 public function delete( $table, $conds, $fname = __METHOD__ ) {
484 $this->mScrollableCursor = false;
485 try {
486 parent::delete( $table, $conds, $fname );
487 } catch ( Exception $e ) {
488 $this->mScrollableCursor = true;
489 throw $e;
490 }
491 $this->mScrollableCursor = true;
492 }
493
494 /**
495 * Estimate rows in dataset
496 * Returns estimated count, based on SHOWPLAN_ALL output
497 * This is not necessarily an accurate estimate, so use sparingly
498 * Returns -1 if count cannot be found
499 * Takes same arguments as Database::select()
500 * @param string $table
501 * @param string $vars
502 * @param string $conds
503 * @param string $fname
504 * @param array $options
505 * @return int
506 */
507 public function estimateRowCount( $table, $vars = '*', $conds = '',
508 $fname = __METHOD__, $options = array()
509 ) {
510 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
511 $options['EXPLAIN'] = true;
512 $options['FOR COUNT'] = true;
513 $res = $this->select( $table, $vars, $conds, $fname, $options );
514
515 $rows = -1;
516 if ( $res ) {
517 $row = $this->fetchRow( $res );
518
519 if ( isset( $row['EstimateRows'] ) ) {
520 $rows = $row['EstimateRows'];
521 }
522 }
523
524 return $rows;
525 }
526
527 /**
528 * Returns information about an index
529 * If errors are explicitly ignored, returns NULL on failure
530 * @param string $table
531 * @param string $index
532 * @param string $fname
533 * @return array|bool|null
534 */
535 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
536 # This does not return the same info as MYSQL would, but that's OK
537 # because MediaWiki never uses the returned value except to check for
538 # the existance of indexes.
539 $sql = "sp_helpindex '" . $table . "'";
540 $res = $this->query( $sql, $fname );
541 if ( !$res ) {
542 return null;
543 }
544
545 $result = array();
546 foreach ( $res as $row ) {
547 if ( $row->index_name == $index ) {
548 $row->Non_unique = !stristr( $row->index_description, "unique" );
549 $cols = explode( ", ", $row->index_keys );
550 foreach ( $cols as $col ) {
551 $row->Column_name = trim( $col );
552 $result[] = clone $row;
553 }
554 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description, 'PRIMARY' ) ) {
555 $row->Non_unique = 0;
556 $cols = explode( ", ", $row->index_keys );
557 foreach ( $cols as $col ) {
558 $row->Column_name = trim( $col );
559 $result[] = clone $row;
560 }
561 }
562 }
563
564 return empty( $result ) ? false : $result;
565 }
566
567 /**
568 * INSERT wrapper, inserts an array into a table
569 *
570 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
571 * multi-row insert.
572 *
573 * Usually aborts on failure
574 * If errors are explicitly ignored, returns success
575 * @param string $table
576 * @param array $arrToInsert
577 * @param string $fname
578 * @param array $options
579 * @throws DBQueryError
580 * @return bool
581 */
582 public function insert( $table, $arrToInsert, $fname = __METHOD__, $options = array() ) {
583 # No rows to insert, easy just return now
584 if ( !count( $arrToInsert ) ) {
585 return true;
586 }
587
588 if ( !is_array( $options ) ) {
589 $options = array( $options );
590 }
591
592 $table = $this->tableName( $table );
593
594 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
595 $arrToInsert = array( 0 => $arrToInsert ); // make everything multi row compatible
596 }
597
598 // We know the table we're inserting into, get its identity column
599 $identity = null;
600 // strip matching square brackets and the db/schema from table name
601 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
602 $tableRaw = array_pop( $tableRawArr );
603 $res = $this->doQuery(
604 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
605 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
606 );
607 if ( $res && sqlsrv_has_rows( $res ) ) {
608 // There is an identity for this table.
609 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC );
610 $identity = array_pop( $identityArr );
611 }
612 sqlsrv_free_stmt( $res );
613
614 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
615 $binaryColumns = $this->getBinaryColumns( $table );
616
617 foreach ( $arrToInsert as $a ) {
618 // start out with empty identity column, this is so we can return
619 // it as a result of the insert logic
620 $sqlPre = '';
621 $sqlPost = '';
622 $identityClause = '';
623
624 // if we have an identity column
625 if ( $identity ) {
626 // iterate through
627 foreach ( $a as $k => $v ) {
628 if ( $k == $identity ) {
629 if ( !is_null( $v ) ) {
630 // there is a value being passed to us,
631 // we need to turn on and off inserted identity
632 $sqlPre = "SET IDENTITY_INSERT $table ON;";
633 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
634 } else {
635 // we can't insert NULL into an identity column,
636 // so remove the column from the insert.
637 unset( $a[$k] );
638 }
639 }
640 }
641
642 // we want to output an identity column as result
643 $identityClause = "OUTPUT INSERTED.$identity ";
644 }
645
646 $keys = array_keys( $a );
647
648 // INSERT IGNORE is not supported by SQL Server
649 // remove IGNORE from options list and set ignore flag to true
650 $ignoreClause = false;
651 if ( in_array( 'IGNORE', $options ) ) {
652 $options = array_diff( $options, array( 'IGNORE' ) );
653 $this->mIgnoreDupKeyErrors = true;
654 }
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 $this->mIgnoreDupKeyErrors = false;
695
696 if ( !is_null( $identity ) ) {
697 // then we want to get the identity column value we were assigned and save it off
698 $row = $ret->fetchObject();
699 $this->mInsertId = $row->$identity;
700 }
701 }
702
703 return $ret;
704 }
705
706 /**
707 * INSERT SELECT wrapper
708 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
709 * Source items may be literals rather than field names, but strings should
710 * be quoted with Database::addQuotes().
711 * @param string $destTable
712 * @param array|string $srcTable May be an array of tables.
713 * @param array $varMap
714 * @param array $conds May be "*" to copy the whole table.
715 * @param string $fname
716 * @param array $insertOptions
717 * @param array $selectOptions
718 * @throws DBQueryError
719 * @return null|ResultWrapper
720 */
721 public function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
722 $insertOptions = array(), $selectOptions = array()
723 ) {
724 $this->mScrollableCursor = false;
725 try {
726 $ret = parent::insertSelect(
727 $destTable,
728 $srcTable,
729 $varMap,
730 $conds,
731 $fname,
732 $insertOptions,
733 $selectOptions
734 );
735 } catch ( Exception $e ) {
736 $this->mScrollableCursor = true;
737 throw $e;
738 }
739 $this->mScrollableCursor = true;
740
741 return $ret;
742 }
743
744 /**
745 * UPDATE wrapper. Takes a condition array and a SET array.
746 *
747 * @param string $table Name of the table to UPDATE. This will be passed through
748 * DatabaseBase::tableName().
749 *
750 * @param array $values An array of values to SET. For each array element,
751 * the key gives the field name, and the value gives the data
752 * to set that field to. The data will be quoted by
753 * DatabaseBase::addQuotes().
754 *
755 * @param array $conds An array of conditions (WHERE). See
756 * DatabaseBase::select() for the details of the format of
757 * condition arrays. Use '*' to update all rows.
758 *
759 * @param string $fname The function name of the caller (from __METHOD__),
760 * for logging and profiling.
761 *
762 * @param array $options An array of UPDATE options, can be:
763 * - IGNORE: Ignore unique key conflicts
764 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
765 * @return bool
766 */
767 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
768 $table = $this->tableName( $table );
769 $binaryColumns = $this->getBinaryColumns( $table );
770
771 $opts = $this->makeUpdateOptions( $options );
772 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET, $binaryColumns );
773
774 if ( $conds !== array() && $conds !== '*' ) {
775 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND, $binaryColumns );
776 }
777
778 $this->mScrollableCursor = false;
779 try {
780 $ret = $this->query( $sql );
781 } catch ( Exception $e ) {
782 $this->mScrollableCursor = true;
783 throw $e;
784 }
785 $this->mScrollableCursor = true;
786 return true;
787 }
788
789 /**
790 * Makes an encoded list of strings from an array
791 * @param array $a Containing the data
792 * @param int $mode Constant
793 * - LIST_COMMA: comma separated, no field names
794 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
795 * the documentation for $conds in DatabaseBase::select().
796 * - LIST_OR: ORed WHERE clause (without the WHERE)
797 * - LIST_SET: comma separated with field names, like a SET clause
798 * - LIST_NAMES: comma separated field names
799 * @param array $binaryColumns Contains a list of column names that are binary types
800 * This is a custom parameter only present for MS SQL.
801 *
802 * @throws MWException|DBUnexpectedError
803 * @return string
804 */
805 public function makeList( $a, $mode = LIST_COMMA, $binaryColumns = array() ) {
806 if ( !is_array( $a ) ) {
807 throw new DBUnexpectedError( $this,
808 'DatabaseBase::makeList called with incorrect parameters' );
809 }
810
811 $first = true;
812 $list = '';
813
814 foreach ( $a as $field => $value ) {
815 if ( $mode != LIST_NAMES && isset( $binaryColumns[$field] ) ) {
816 if ( is_array( $value ) ) {
817 foreach ( $value as &$v ) {
818 $v = new MssqlBlob( $v );
819 }
820 } else {
821 $value = new MssqlBlob( $value );
822 }
823 }
824
825 if ( !$first ) {
826 if ( $mode == LIST_AND ) {
827 $list .= ' AND ';
828 } elseif ( $mode == LIST_OR ) {
829 $list .= ' OR ';
830 } else {
831 $list .= ',';
832 }
833 } else {
834 $first = false;
835 }
836
837 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
838 $list .= "($value)";
839 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
840 $list .= "$value";
841 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
842 if ( count( $value ) == 0 ) {
843 throw new MWException( __METHOD__ . ": empty input for field $field" );
844 } elseif ( count( $value ) == 1 ) {
845 // Special-case single values, as IN isn't terribly efficient
846 // Don't necessarily assume the single key is 0; we don't
847 // enforce linear numeric ordering on other arrays here.
848 $value = array_values( $value );
849 $list .= $field . " = " . $this->addQuotes( $value[0] );
850 } else {
851 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
852 }
853 } elseif ( $value === null ) {
854 if ( $mode == LIST_AND || $mode == LIST_OR ) {
855 $list .= "$field IS ";
856 } elseif ( $mode == LIST_SET ) {
857 $list .= "$field = ";
858 }
859 $list .= 'NULL';
860 } else {
861 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
862 $list .= "$field = ";
863 }
864 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
865 }
866 }
867
868 return $list;
869 }
870
871 /**
872 * @param string $table
873 * @param string $field
874 * @return int Returns the size of a text field, or -1 for "unlimited"
875 */
876 public function textFieldSize( $table, $field ) {
877 $table = $this->tableName( $table );
878 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
879 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
880 $res = $this->query( $sql );
881 $row = $this->fetchRow( $res );
882 $size = -1;
883 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
884 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
885 }
886
887 return $size;
888 }
889
890 /**
891 * Construct a LIMIT query with optional offset
892 * This is used for query pages
893 *
894 * @param string $sql SQL query we will append the limit too
895 * @param int $limit The SQL limit
896 * @param bool|int $offset The SQL offset (default false)
897 * @return array|string
898 */
899 public function limitResult( $sql, $limit, $offset = false ) {
900 if ( $offset === false || $offset == 0 ) {
901 if ( strpos( $sql, "SELECT" ) === false ) {
902 return "TOP {$limit} " . $sql;
903 } else {
904 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
905 'SELECT$1 TOP ' . $limit, $sql, 1 );
906 }
907 } else {
908 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
909 $select = $orderby = array();
910 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
911 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
912 $overOrder = $postOrder = '';
913 $first = $offset + 1;
914 $last = $offset + $limit;
915 $sub1 = 'sub_' . $this->mSubqueryId;
916 $sub2 = 'sub_' . ( $this->mSubqueryId + 1 );
917 $this->mSubqueryId += 2;
918 if ( !$s1 ) {
919 // wat
920 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
921 }
922 if ( !$s2 ) {
923 // no ORDER BY
924 $overOrder = 'ORDER BY 1';
925 } else {
926 if ( !isset( $orderby[2] ) || !$orderby[2] ) {
927 // don't need to strip it out if we're using a FOR XML clause
928 $sql = str_replace( $orderby[1], '', $sql );
929 }
930 $overOrder = $orderby[1];
931 $postOrder = ' ' . $overOrder;
932 }
933 $sql = "SELECT {$select[1]}
934 FROM (
935 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
936 FROM ({$sql}) {$sub1}
937 ) {$sub2}
938 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
939
940 return $sql;
941 }
942 }
943
944 /**
945 * If there is a limit clause, parse it, strip it, and pass the remaining
946 * SQL through limitResult() with the appropriate parameters. Not the
947 * prettiest solution, but better than building a whole new parser. This
948 * exists becase there are still too many extensions that don't use dynamic
949 * sql generation.
950 *
951 * @param string $sql
952 * @return array|mixed|string
953 */
954 public function LimitToTopN( $sql ) {
955 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
956 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
957 if ( preg_match( $pattern, $sql, $matches ) ) {
958 // row_count = $matches[4]
959 $row_count = $matches[4];
960 // offset = $matches[3] OR $matches[6]
961 $offset = $matches[3] or
962 $offset = $matches[6] or
963 $offset = false;
964
965 // strip the matching LIMIT clause out
966 $sql = str_replace( $matches[0], '', $sql );
967
968 return $this->limitResult( $sql, $row_count, $offset );
969 }
970
971 return $sql;
972 }
973
974 /**
975 * @return string Wikitext of a link to the server software's web site
976 */
977 public function getSoftwareLink() {
978 return "[{{int:version-db-mssql-url}} MS SQL Server]";
979 }
980
981 /**
982 * @return string Version information from the database
983 */
984 public function getServerVersion() {
985 $server_info = sqlsrv_server_info( $this->mConn );
986 $version = 'Error';
987 if ( isset( $server_info['SQLServerVersion'] ) ) {
988 $version = $server_info['SQLServerVersion'];
989 }
990
991 return $version;
992 }
993
994 /**
995 * @param string $table
996 * @param string $fname
997 * @return bool
998 */
999 public function tableExists( $table, $fname = __METHOD__ ) {
1000 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1001
1002 if ( $db !== false ) {
1003 // remote database
1004 wfDebug( "Attempting to call tableExists on a remote table" );
1005 return false;
1006 }
1007
1008 if ( $schema === false ) {
1009 global $wgDBmwschema;
1010 $schema = $wgDBmwschema;
1011 }
1012
1013 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1014 WHERE TABLE_TYPE = 'BASE TABLE'
1015 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1016
1017 if ( $res->numRows() ) {
1018 return true;
1019 } else {
1020 return false;
1021 }
1022 }
1023
1024 /**
1025 * Query whether a given column exists in the mediawiki schema
1026 * @param string $table
1027 * @param string $field
1028 * @param string $fname
1029 * @return bool
1030 */
1031 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1032 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1033
1034 if ( $db !== false ) {
1035 // remote database
1036 wfDebug( "Attempting to call fieldExists on a remote table" );
1037 return false;
1038 }
1039
1040 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1041 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1042
1043 if ( $res->numRows() ) {
1044 return true;
1045 } else {
1046 return false;
1047 }
1048 }
1049
1050 public function fieldInfo( $table, $field ) {
1051 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1052
1053 if ( $db !== false ) {
1054 // remote database
1055 wfDebug( "Attempting to call fieldInfo on a remote table" );
1056 return false;
1057 }
1058
1059 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1060 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1061
1062 $meta = $res->fetchRow();
1063 if ( $meta ) {
1064 return new MssqlField( $meta );
1065 }
1066
1067 return false;
1068 }
1069
1070 /**
1071 * Begin a transaction, committing any previously open transaction
1072 * @param string $fname
1073 */
1074 protected function doBegin( $fname = __METHOD__ ) {
1075 sqlsrv_begin_transaction( $this->mConn );
1076 $this->mTrxLevel = 1;
1077 }
1078
1079 /**
1080 * End a transaction
1081 * @param string $fname
1082 */
1083 protected function doCommit( $fname = __METHOD__ ) {
1084 sqlsrv_commit( $this->mConn );
1085 $this->mTrxLevel = 0;
1086 }
1087
1088 /**
1089 * Rollback a transaction.
1090 * No-op on non-transactional databases.
1091 * @param string $fname
1092 */
1093 protected function doRollback( $fname = __METHOD__ ) {
1094 sqlsrv_rollback( $this->mConn );
1095 $this->mTrxLevel = 0;
1096 }
1097
1098 /**
1099 * Escapes a identifier for use inm SQL.
1100 * Throws an exception if it is invalid.
1101 * Reference: http://msdn.microsoft.com/en-us/library/aa224033%28v=SQL.80%29.aspx
1102 * @param string $identifier
1103 * @throws MWException
1104 * @return string
1105 */
1106 private function escapeIdentifier( $identifier ) {
1107 if ( strlen( $identifier ) == 0 ) {
1108 throw new MWException( "An identifier must not be empty" );
1109 }
1110 if ( strlen( $identifier ) > 128 ) {
1111 throw new MWException( "The identifier '$identifier' is too long (max. 128)" );
1112 }
1113 if ( ( strpos( $identifier, '[' ) !== false )
1114 || ( strpos( $identifier, ']' ) !== false )
1115 ) {
1116 // It may be allowed if you quoted with double quotation marks, but
1117 // that would break if QUOTED_IDENTIFIER is OFF
1118 throw new MWException( "Square brackets are not allowed in '$identifier'" );
1119 }
1120
1121 return "[$identifier]";
1122 }
1123
1124 /**
1125 * @param string $s
1126 * @return string
1127 */
1128 public function strencode( $s ) { # Should not be called by us
1129 return str_replace( "'", "''", $s );
1130 }
1131
1132 /**
1133 * @param string $s
1134 * @return string
1135 */
1136 public function addQuotes( $s ) {
1137 if ( $s instanceof MssqlBlob ) {
1138 return $s->fetch();
1139 } elseif ( $s instanceof Blob ) {
1140 // this shouldn't really ever be called, but it's here if needed
1141 // (and will quite possibly make the SQL error out)
1142 $blob = new MssqlBlob( $s->fetch() );
1143 return $blob->fetch();
1144 } else {
1145 if ( is_bool( $s ) ) {
1146 $s = $s ? 1 : 0;
1147 }
1148 return parent::addQuotes( $s );
1149 }
1150 }
1151
1152 /**
1153 * @param string $s
1154 * @return string
1155 */
1156 public function addIdentifierQuotes( $s ) {
1157 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1158 return '[' . $s . ']';
1159 }
1160
1161 /**
1162 * @param string $name
1163 * @return bool
1164 */
1165 public function isQuotedIdentifier( $name ) {
1166 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1167 }
1168
1169 /**
1170 * @param string $db
1171 * @return bool
1172 */
1173 public function selectDB( $db ) {
1174 try {
1175 $this->mDBname = $db;
1176 $this->query( "USE $db" );
1177 return true;
1178 } catch ( Exception $e ) {
1179 return false;
1180 }
1181 }
1182
1183 /**
1184 * @param array $options An associative array of options to be turned into
1185 * an SQL query, valid keys are listed in the function.
1186 * @return array
1187 */
1188 public function makeSelectOptions( $options ) {
1189 $tailOpts = '';
1190 $startOpts = '';
1191
1192 $noKeyOptions = array();
1193 foreach ( $options as $key => $option ) {
1194 if ( is_numeric( $key ) ) {
1195 $noKeyOptions[$option] = true;
1196 }
1197 }
1198
1199 $tailOpts .= $this->makeGroupByWithHaving( $options );
1200
1201 $tailOpts .= $this->makeOrderBy( $options );
1202
1203 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1204 $startOpts .= 'DISTINCT';
1205 }
1206
1207 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1208 // used in group concat field emulation
1209 $tailOpts .= " FOR XML PATH('')";
1210 }
1211
1212 // we want this to be compatible with the output of parent::makeSelectOptions()
1213 return array( $startOpts, '', $tailOpts, '' );
1214 }
1215
1216 /**
1217 * Get the type of the DBMS, as it appears in $wgDBtype.
1218 * @return string
1219 */
1220 public function getType() {
1221 return 'mssql';
1222 }
1223
1224 /**
1225 * @param array $stringList
1226 * @return string
1227 */
1228 public function buildConcat( $stringList ) {
1229 return implode( ' + ', $stringList );
1230 }
1231
1232 /**
1233 * Build a GROUP_CONCAT or equivalent statement for a query.
1234 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1235 *
1236 * This is useful for combining a field for several rows into a single string.
1237 * NULL values will not appear in the output, duplicated values will appear,
1238 * and the resulting delimiter-separated values have no defined sort order.
1239 * Code using the results may need to use the PHP unique() or sort() methods.
1240 *
1241 * @param string $delim Glue to bind the results together
1242 * @param string|array $table Table name
1243 * @param string $field Field name
1244 * @param string|array $conds Conditions
1245 * @param string|array $join_conds Join conditions
1246 * @return string SQL text
1247 * @since 1.23
1248 */
1249 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1250 $join_conds = array()
1251 ) {
1252 $gcsq = 'gcsq_' . $this->mSubqueryId;
1253 $this->mSubqueryId++;
1254
1255 $delimLen = strlen( $delim );
1256 $fld = "{$field} + {$this->addQuotes( $delim )}";
1257 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1258 . $this->selectSQLText( $table, $fld, $conds, null, array( 'FOR XML' ), $join_conds )
1259 . ") {$gcsq} ({$field}))";
1260
1261 return $sql;
1262 }
1263
1264 /**
1265 * @return string
1266 */
1267 public function getSearchEngine() {
1268 return "SearchMssql";
1269 }
1270
1271 /**
1272 * Returns an associative array for fields that are of type varbinary, binary, or image
1273 * $table can be either a raw table name or passed through tableName() first
1274 * @param string $table
1275 * @return array
1276 */
1277 private function getBinaryColumns( $table ) {
1278 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1279 $tableRaw = array_pop( $tableRawArr );
1280
1281 if ( $this->mBinaryColumnCache === null ) {
1282 $this->populateColumnCaches();
1283 }
1284
1285 return isset( $this->mBinaryColumnCache[$tableRaw] )
1286 ? $this->mBinaryColumnCache[$tableRaw]
1287 : array();
1288 }
1289
1290 /**
1291 * @param string $table
1292 * @return array
1293 */
1294 private function getBitColumns( $table ) {
1295 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1296 $tableRaw = array_pop( $tableRawArr );
1297
1298 if ( $this->mBitColumnCache === null ) {
1299 $this->populateColumnCaches();
1300 }
1301
1302 return isset( $this->mBitColumnCache[$tableRaw] )
1303 ? $this->mBitColumnCache[$tableRaw]
1304 : array();
1305 }
1306
1307 private function populateColumnCaches() {
1308 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1309 array(
1310 'TABLE_CATALOG' => $this->mDBname,
1311 'TABLE_SCHEMA' => $this->mSchema,
1312 'DATA_TYPE' => array( 'varbinary', 'binary', 'image', 'bit' )
1313 ) );
1314
1315 $this->mBinaryColumnCache = array();
1316 $this->mBitColumnCache = array();
1317 foreach ( $res as $row ) {
1318 if ( $row->DATA_TYPE == 'bit' ) {
1319 $this->mBitColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1320 } else {
1321 $this->mBinaryColumnCache[$row->TABLE_NAME][$row->COLUMN_NAME] = $row;
1322 }
1323 }
1324 }
1325
1326 /**
1327 * @param string $name
1328 * @param string $format
1329 * @return string
1330 */
1331 function tableName( $name, $format = 'quoted' ) {
1332 # Replace reserved words with better ones
1333 switch ( $name ) {
1334 case 'user':
1335 return $this->realTableName( 'mwuser', $format );
1336 default:
1337 return $this->realTableName( $name, $format );
1338 }
1339 }
1340
1341 /**
1342 * call this instead of tableName() in the updater when renaming tables
1343 * @param string $name
1344 * @param string $format One of quoted, raw, or split
1345 * @return string
1346 */
1347 function realTableName( $name, $format = 'quoted' ) {
1348 $table = parent::tableName( $name, $format );
1349 if ( $format == 'split' ) {
1350 // Used internally, we want the schema split off from the table name and returned
1351 // as a list with 3 elements (database, schema, table)
1352 $table = explode( '.', $table );
1353 while ( count( $table ) < 3 ) {
1354 array_unshift( $table, false );
1355 }
1356 }
1357 return $table;
1358 }
1359
1360 /**
1361 * Called in the installer and updater.
1362 * Probably doesn't need to be called anywhere else in the codebase.
1363 * @param bool|null $value
1364 * @return bool|null
1365 */
1366 public function prepareStatements( $value = null ) {
1367 return wfSetVar( $this->mPrepareStatements, $value );
1368 }
1369
1370 /**
1371 * Called in the installer and updater.
1372 * Probably doesn't need to be called anywhere else in the codebase.
1373 * @param bool|null $value
1374 * @return bool|null
1375 */
1376 public function scrollableCursor( $value = null ) {
1377 return wfSetVar( $this->mScrollableCursor, $value );
1378 }
1379 } // end DatabaseMssql class
1380
1381 /**
1382 * Utility class.
1383 *
1384 * @ingroup Database
1385 */
1386 class MssqlField implements Field {
1387 private $name, $tableName, $default, $max_length, $nullable, $type;
1388
1389 function __construct( $info ) {
1390 $this->name = $info['COLUMN_NAME'];
1391 $this->tableName = $info['TABLE_NAME'];
1392 $this->default = $info['COLUMN_DEFAULT'];
1393 $this->max_length = $info['CHARACTER_MAXIMUM_LENGTH'];
1394 $this->nullable = !( strtolower( $info['IS_NULLABLE'] ) == 'no' );
1395 $this->type = $info['DATA_TYPE'];
1396 }
1397
1398 function name() {
1399 return $this->name;
1400 }
1401
1402 function tableName() {
1403 return $this->tableName;
1404 }
1405
1406 function defaultValue() {
1407 return $this->default;
1408 }
1409
1410 function maxLength() {
1411 return $this->max_length;
1412 }
1413
1414 function isNullable() {
1415 return $this->nullable;
1416 }
1417
1418 function type() {
1419 return $this->type;
1420 }
1421 }
1422
1423 class MssqlBlob extends Blob {
1424 public function __construct( $data ) {
1425 if ( $data instanceof MssqlBlob ) {
1426 return $data;
1427 } elseif ( $data instanceof Blob ) {
1428 $this->mData = $data->fetch();
1429 } elseif ( is_array( $data ) && is_object( $data ) ) {
1430 $this->mData = serialize( $data );
1431 } else {
1432 $this->mData = $data;
1433 }
1434 }
1435
1436 /**
1437 * Returns an unquoted hex representation of a binary string
1438 * for insertion into varbinary-type fields
1439 * @return string
1440 */
1441 public function fetch() {
1442 if ( $this->mData === null ) {
1443 return 'null';
1444 }
1445
1446 $ret = '0x';
1447 $dataLength = strlen( $this->mData );
1448 for ( $i = 0; $i < $dataLength; $i++ ) {
1449 $ret .= bin2hex( pack( 'C', ord( $this->mData[$i] ) ) );
1450 }
1451
1452 return $ret;
1453 }
1454 }
1455
1456 class MssqlResultWrapper extends ResultWrapper {
1457 private $mSeekTo = null;
1458
1459 /**
1460 * @return stdClass|bool
1461 */
1462 public function fetchObject() {
1463 $res = $this->result;
1464
1465 if ( $this->mSeekTo !== null ) {
1466 $result = sqlsrv_fetch_object( $res, 'stdClass', array(),
1467 SQLSRV_SCROLL_ABSOLUTE, $this->mSeekTo );
1468 $this->mSeekTo = null;
1469 } else {
1470 $result = sqlsrv_fetch_object( $res );
1471 }
1472
1473 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1474 if ( $result === null ) {
1475 return false;
1476 }
1477
1478 return $result;
1479 }
1480
1481 /**
1482 * @return array|bool
1483 */
1484 public function fetchRow() {
1485 $res = $this->result;
1486
1487 if ( $this->mSeekTo !== null ) {
1488 $result = sqlsrv_fetch_array( $res, SQLSRV_FETCH_BOTH,
1489 SQLSRV_SCROLL_ABSOLUTE, $this->mSeekTo );
1490 $this->mSeekTo = null;
1491 } else {
1492 $result = sqlsrv_fetch_array( $res );
1493 }
1494
1495 // MediaWiki expects us to return boolean false when there are no more rows instead of null
1496 if ( $result === null ) {
1497 return false;
1498 }
1499
1500 return $result;
1501 }
1502
1503 /**
1504 * @param int $row
1505 * @return bool
1506 */
1507 public function seek( $row ) {
1508 $res = $this->result;
1509
1510 // check bounds
1511 $numRows = $this->db->numRows( $res );
1512 $row = intval( $row );
1513
1514 if ( $numRows === 0 ) {
1515 return false;
1516 } elseif ( $row < 0 || $row > $numRows - 1 ) {
1517 return false;
1518 }
1519
1520 // Unlike MySQL, the seek actually happens on the next access
1521 $this->mSeekTo = $row;
1522 return true;
1523 }
1524 }