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