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