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