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