3 * This is the MySQL database abstraction layer.
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.
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.
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
25 * Database abstraction object for MySQL.
26 * Defines methods independent on used MySQL extension.
32 abstract class DatabaseMysqlBase
extends DatabaseBase
{
33 /** @var MysqlMasterPos */
34 protected $lastKnownSlavePos;
44 * @param $server string
46 * @param $password string
47 * @param $dbName string
49 * @throws DBConnectionError
51 function open( $server, $user, $password, $dbName ) {
52 global $wgAllDBsAreLocalhost, $wgDBmysql5, $wgSQLMode;
53 wfProfileIn( __METHOD__
);
55 # Debugging hack -- fake cluster
56 if ( $wgAllDBsAreLocalhost ) {
57 $realServer = 'localhost';
59 $realServer = $server;
62 $this->mServer
= $server;
64 $this->mPassword
= $password;
65 $this->mDBname
= $dbName;
67 wfProfileIn( "dbconnect-$server" );
69 # The kernel's default SYN retransmission period is far too slow for us,
70 # so we use a short timeout plus a manual retry. Retrying means that a small
71 # but finite rate of SYN packet loss won't cause user-visible errors.
73 $this->installErrorHandler();
75 $this->mConn
= $this->mysqlConnect( $realServer );
76 } catch ( Exception
$ex ) {
77 wfProfileOut( "dbconnect-$server" );
78 wfProfileOut( __METHOD__
);
79 $this->restoreErrorHandler();
82 $error = $this->restoreErrorHandler();
84 wfProfileOut( "dbconnect-$server" );
86 # Always log connection errors
87 if ( !$this->mConn
) {
89 $error = $this->lastError();
91 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
92 wfDebug( "DB connection error\n" .
93 "Server: $server, User: $user, Password: " .
94 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
96 wfProfileOut( __METHOD__
);
98 return $this->reportConnectionError( $error );
101 if ( $dbName != '' ) {
102 wfSuppressWarnings();
103 $success = $this->selectDB( $dbName );
106 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
107 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
108 "from client host " . wfHostname() . "\n" );
110 wfProfileOut( __METHOD__
);
112 return $this->reportConnectionError( "Error selecting database $dbName" );
116 // Tell the server we're communicating with it in UTF-8.
117 // This may engage various charset conversions.
119 $this->mysqlSetCharset( 'utf8' );
121 $this->mysqlSetCharset( 'binary' );
123 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
124 if ( is_string( $wgSQLMode ) ) {
125 $mode = $this->addQuotes( $wgSQLMode );
126 // Use doQuery() to avoid opening implicit transactions (DBO_TRX)
127 $success = $this->doQuery( "SET sql_mode = $mode", __METHOD__
);
129 wfLogDBError( "Error setting sql_mode to $mode on server {$this->mServer}" );
130 wfProfileOut( __METHOD__
);
131 return $this->reportConnectionError( "Error setting sql_mode to $mode" );
135 $this->mOpened
= true;
136 wfProfileOut( __METHOD__
);
142 * Open a connection to a MySQL server
144 * @param $realServer string
145 * @return mixed Raw connection
146 * @throws DBConnectionError
148 abstract protected function mysqlConnect( $realServer );
151 * Set the character set of the MySQL link
153 * @param string $charset
156 abstract protected function mysqlSetCharset( $charset );
159 * @param $res ResultWrapper
160 * @throws DBUnexpectedError
162 function freeResult( $res ) {
163 if ( $res instanceof ResultWrapper
) {
166 wfSuppressWarnings();
167 $ok = $this->mysqlFreeResult( $res );
170 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
177 * @param $res Raw result
180 abstract protected function mysqlFreeResult( $res );
183 * @param $res ResultWrapper
184 * @return object|bool
185 * @throws DBUnexpectedError
187 function fetchObject( $res ) {
188 if ( $res instanceof ResultWrapper
) {
191 wfSuppressWarnings();
192 $row = $this->mysqlFetchObject( $res );
195 $errno = $this->lastErrno();
196 // Unfortunately, mysql_fetch_object does not reset the last errno.
197 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
198 // these are the only errors mysql_fetch_object can cause.
199 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
200 if ( $errno == 2000 ||
$errno == 2013 ) {
201 throw new DBUnexpectedError(
203 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
211 * Fetch a result row as an object
213 * @param $res Raw result
216 abstract protected function mysqlFetchObject( $res );
219 * @param $res ResultWrapper
221 * @throws DBUnexpectedError
223 function fetchRow( $res ) {
224 if ( $res instanceof ResultWrapper
) {
227 wfSuppressWarnings();
228 $row = $this->mysqlFetchArray( $res );
231 $errno = $this->lastErrno();
232 // Unfortunately, mysql_fetch_array does not reset the last errno.
233 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
234 // these are the only errors mysql_fetch_array can cause.
235 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
236 if ( $errno == 2000 ||
$errno == 2013 ) {
237 throw new DBUnexpectedError(
239 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
247 * Fetch a result row as an associative and numeric array
249 * @param $res Raw result
252 abstract protected function mysqlFetchArray( $res );
255 * @throws DBUnexpectedError
256 * @param $res ResultWrapper
259 function numRows( $res ) {
260 if ( $res instanceof ResultWrapper
) {
263 wfSuppressWarnings();
264 $n = $this->mysqlNumRows( $res );
267 // Unfortunately, mysql_num_rows does not reset the last errno.
268 // We are not checking for any errors here, since
269 // these are no errors mysql_num_rows can cause.
270 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
271 // See https://bugzilla.wikimedia.org/42430
276 * Get number of rows in result
278 * @param $res Raw result
281 abstract protected function mysqlNumRows( $res );
284 * @param $res ResultWrapper
287 function numFields( $res ) {
288 if ( $res instanceof ResultWrapper
) {
292 return $this->mysqlNumFields( $res );
296 * Get number of fields in result
298 * @param $res Raw result
301 abstract protected function mysqlNumFields( $res );
304 * @param $res ResultWrapper
308 function fieldName( $res, $n ) {
309 if ( $res instanceof ResultWrapper
) {
313 return $this->mysqlFieldName( $res, $n );
317 * Get the name of the specified field in a result
319 * @param $res Raw result
323 abstract protected function mysqlFieldName( $res, $n );
326 * @param $res ResultWrapper
330 function dataSeek( $res, $row ) {
331 if ( $res instanceof ResultWrapper
) {
335 return $this->mysqlDataSeek( $res, $row );
339 * Move internal result pointer
341 * @param $res Raw result
345 abstract protected function mysqlDataSeek( $res, $row );
350 function lastError() {
351 if ( $this->mConn
) {
352 # Even if it's non-zero, it can still be invalid
353 wfSuppressWarnings();
354 $error = $this->mysqlError( $this->mConn
);
356 $error = $this->mysqlError();
360 $error = $this->mysqlError();
363 $error .= ' (' . $this->mServer
. ')';
370 * Returns the text of the error message from previous MySQL operation
372 * @param $conn Raw connection
375 abstract protected function mysqlError( $conn = null );
378 * @param $table string
379 * @param $uniqueIndexes
381 * @param $fname string
382 * @return ResultWrapper
384 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
385 return $this->nativeReplace( $table, $rows, $fname );
389 * Estimate rows in dataset
390 * Returns estimated count, based on EXPLAIN output
391 * Takes same arguments as Database::select()
393 * @param $table string|array
394 * @param $vars string|array
395 * @param $conds string|array
396 * @param $fname string
397 * @param $options string|array
400 public function estimateRowCount( $table, $vars = '*', $conds = '',
401 $fname = __METHOD__
, $options = array()
403 $options['EXPLAIN'] = true;
404 $res = $this->select( $table, $vars, $conds, $fname, $options );
405 if ( $res === false ) {
408 if ( !$this->numRows( $res ) ) {
413 foreach ( $res as $plan ) {
414 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
421 * @param $table string
422 * @param $field string
423 * @return bool|MySQLField
425 function fieldInfo( $table, $field ) {
426 $table = $this->tableName( $table );
427 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
431 $n = $this->mysqlNumFields( $res->result
);
432 for ( $i = 0; $i < $n; $i++
) {
433 $meta = $this->mysqlFetchField( $res->result
, $i );
434 if ( $field == $meta->name
) {
435 return new MySQLField( $meta );
443 * Get column information from a result
445 * @param $res Raw result
449 abstract protected function mysqlFetchField( $res, $n );
452 * Get information about an index into an object
453 * Returns false if the index does not exist
455 * @param $table string
456 * @param $index string
457 * @param $fname string
458 * @return bool|array|null False or null on failure
460 function indexInfo( $table, $index, $fname = __METHOD__
) {
461 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
462 # SHOW INDEX should work for 3.x and up:
463 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
464 $table = $this->tableName( $table );
465 $index = $this->indexName( $index );
467 $sql = 'SHOW INDEX FROM ' . $table;
468 $res = $this->query( $sql, $fname );
476 foreach ( $res as $row ) {
477 if ( $row->Key_name
== $index ) {
482 return empty( $result ) ?
false : $result;
490 function strencode( $s ) {
491 $sQuoted = $this->mysqlRealEscapeString( $s );
493 if ( $sQuoted === false ) {
495 $sQuoted = $this->mysqlRealEscapeString( $s );
502 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
508 public function addIdentifierQuotes( $s ) {
509 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
510 // Remove NUL bytes and escape backticks by doubling
511 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
515 * @param $name string
518 public function isQuotedIdentifier( $name ) {
519 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
526 $ping = $this->mysqlPing();
531 $this->closeConnection();
532 $this->mOpened
= false;
533 $this->mConn
= false;
534 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
540 * Ping a server connection or reconnect if there is no connection
544 abstract protected function mysqlPing();
549 * This will do a SHOW SLAVE STATUS
554 if ( !is_null( $this->mFakeSlaveLag
) ) {
555 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
557 return $this->mFakeSlaveLag
;
560 return $this->getLagFromSlaveStatus();
566 function getLagFromSlaveStatus() {
567 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
571 $row = $res->fetchObject();
575 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
578 return intval( $row->Seconds_Behind_Master
);
583 * @deprecated in 1.19, use getLagFromSlaveStatus
587 function getLagFromProcesslist() {
588 wfDeprecated( __METHOD__
, '1.19' );
589 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
593 # Find slave SQL thread
594 foreach ( $res as $row ) {
595 /* This should work for most situations - when default db
596 * for thread is not specified, it had no events executed,
597 * and therefore it doesn't know yet how lagged it is.
599 * Relay log I/O thread does not select databases.
601 if ( $row->User
== 'system user' &&
602 $row->State
!= 'Waiting for master to send event' &&
603 $row->State
!= 'Connecting to master' &&
604 $row->State
!= 'Queueing master event to the relay log' &&
605 $row->State
!= 'Waiting for master update' &&
606 $row->State
!= 'Requesting binlog dump' &&
607 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
608 $row->State
!= 'Reconnecting after a failed master event read' &&
609 $row->State
!= 'Registering slave on master'
611 # This is it, return the time (except -ve)
612 if ( $row->Time
> 0x7fffffff ) {
624 * Wait for the slave to catch up to a given master position.
625 * @TODO: return values for this and base class are rubbish
627 * @param $pos DBMasterPos object
628 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
629 * @return bool|string
631 function masterPosWait( DBMasterPos
$pos, $timeout ) {
632 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
633 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
636 wfProfileIn( __METHOD__
);
637 # Commit any open transactions
638 $this->commit( __METHOD__
, 'flush' );
640 if ( !is_null( $this->mFakeSlaveLag
) ) {
641 $status = parent
::masterPosWait( $pos, $timeout );
642 wfProfileOut( __METHOD__
);
647 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
648 $encFile = $this->addQuotes( $pos->file
);
649 $encPos = intval( $pos->pos
);
650 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
651 $res = $this->doQuery( $sql );
654 if ( $res && $row = $this->fetchRow( $res ) ) {
655 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
656 if ( ctype_digit( $status ) ) { // success
657 $this->lastKnownSlavePos
= $pos;
661 wfProfileOut( __METHOD__
);
667 * Get the position of the master from SHOW SLAVE STATUS
669 * @return MySQLMasterPos|bool
671 function getSlavePos() {
672 if ( !is_null( $this->mFakeSlaveLag
) ) {
673 return parent
::getSlavePos();
676 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
677 $row = $this->fetchObject( $res );
680 $pos = isset( $row->Exec_master_log_pos
)
681 ?
$row->Exec_master_log_pos
682 : $row->Exec_Master_Log_Pos
;
684 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
691 * Get the position of the master from SHOW MASTER STATUS
693 * @return MySQLMasterPos|bool
695 function getMasterPos() {
696 if ( $this->mFakeMaster
) {
697 return parent
::getMasterPos();
700 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
701 $row = $this->fetchObject( $res );
704 return new MySQLMasterPos( $row->File
, $row->Position
);
714 function useIndexClause( $index ) {
715 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
721 function lowPriorityOption() {
722 return 'LOW_PRIORITY';
728 public function getSoftwareLink() {
729 return '[http://www.mysql.com/ MySQL]';
733 * @param $options array
735 public function setSessionOptions( array $options ) {
736 if ( isset( $options['connTimeout'] ) ) {
737 $timeout = (int)$options['connTimeout'];
738 $this->query( "SET net_read_timeout=$timeout" );
739 $this->query( "SET net_write_timeout=$timeout" );
743 public function streamStatementEnd( &$sql, &$newLine ) {
744 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
745 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
746 $this->delimiter
= $m[1];
750 return parent
::streamStatementEnd( $sql, $newLine );
754 * Check to see if a named lock is available. This is non-blocking.
756 * @param string $lockName name of lock to poll
757 * @param string $method name of method calling us
761 public function lockIsFree( $lockName, $method ) {
762 $lockName = $this->addQuotes( $lockName );
763 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
764 $row = $this->fetchObject( $result );
766 return ( $row->lockstatus
== 1 );
770 * @param $lockName string
771 * @param $method string
772 * @param $timeout int
775 public function lock( $lockName, $method, $timeout = 5 ) {
776 $lockName = $this->addQuotes( $lockName );
777 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
778 $row = $this->fetchObject( $result );
780 if ( $row->lockstatus
== 1 ) {
783 wfDebug( __METHOD__
. " failed to acquire lock\n" );
791 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
792 * @param $lockName string
793 * @param $method string
796 public function unlock( $lockName, $method ) {
797 $lockName = $this->addQuotes( $lockName );
798 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
799 $row = $this->fetchObject( $result );
801 return ( $row->lockstatus
== 1 );
806 * @param $write array
807 * @param $method string
808 * @param $lowPriority bool
811 public function lockTables( $read, $write, $method, $lowPriority = true ) {
814 foreach ( $write as $table ) {
815 $tbl = $this->tableName( $table ) .
816 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
820 foreach ( $read as $table ) {
821 $items[] = $this->tableName( $table ) . ' READ';
823 $sql = "LOCK TABLES " . implode( ',', $items );
824 $this->query( $sql, $method );
830 * @param $method string
833 public function unlockTables( $method ) {
834 $this->query( "UNLOCK TABLES", $method );
840 * Get search engine class. All subclasses of this
841 * need to implement this if they wish to use searching.
845 public function getSearchEngine() {
846 return 'SearchMySQL';
853 public function setBigSelects( $value = true ) {
854 if ( $value === 'default' ) {
855 if ( $this->mDefaultBigSelects
=== null ) {
856 # Function hasn't been called before so it must already be set to the default
859 $value = $this->mDefaultBigSelects
;
861 } elseif ( $this->mDefaultBigSelects
=== null ) {
862 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
864 $encValue = $value ?
'1' : '0';
865 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
869 * DELETE where the condition is a join. MySql uses multi-table deletes.
870 * @param $delTable string
871 * @param $joinTable string
872 * @param $delVar string
873 * @param $joinVar string
874 * @param $conds array|string
875 * @param bool|string $fname bool
876 * @throws DBUnexpectedError
877 * @return bool|ResultWrapper
879 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
881 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
884 $delTable = $this->tableName( $delTable );
885 $joinTable = $this->tableName( $joinTable );
886 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
888 if ( $conds != '*' ) {
889 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
892 return $this->query( $sql, $fname );
896 * @param string $table
898 * @param array $uniqueIndexes
900 * @param string $fname
901 * @param array $options
904 public function upsert(
905 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
907 if ( !count( $rows ) ) {
908 return true; // nothing to do
910 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
912 $table = $this->tableName( $table );
913 $columns = array_keys( $rows[0] );
915 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
916 $rowTuples = array();
917 foreach ( $rows as $row ) {
918 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
920 $sql .= implode( ',', $rowTuples );
921 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
923 return (bool)$this->query( $sql, $fname );
927 * Determines how long the server has been up
931 function getServerUptime() {
932 $vars = $this->getMysqlStatus( 'Uptime' );
934 return (int)$vars['Uptime'];
938 * Determines if the last failure was due to a deadlock
942 function wasDeadlock() {
943 return $this->lastErrno() == 1213;
947 * Determines if the last failure was due to a lock timeout
951 function wasLockTimeout() {
952 return $this->lastErrno() == 1205;
956 * Determines if the last query error was something that should be dealt
957 * with by pinging the connection and reissuing the query
961 function wasErrorReissuable() {
962 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
966 * Determines if the last failure was due to the database being read-only.
970 function wasReadOnlyError() {
971 return $this->lastErrno() == 1223 ||
972 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
978 * @param $temporary bool
979 * @param $fname string
981 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
982 $tmp = $temporary ?
'TEMPORARY ' : '';
983 $newName = $this->addIdentifierQuotes( $newName );
984 $oldName = $this->addIdentifierQuotes( $oldName );
985 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
986 $this->query( $query, $fname );
990 * List all tables on the database
992 * @param string $prefix Only show tables with this prefix, e.g. mw_
993 * @param string $fname calling function name
996 function listTables( $prefix = null, $fname = __METHOD__
) {
997 $result = $this->query( "SHOW TABLES", $fname );
1001 foreach ( $result as $table ) {
1002 $vars = get_object_vars( $table );
1003 $table = array_pop( $vars );
1005 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1006 $endArray[] = $table;
1015 * @param $fName string
1016 * @return bool|ResultWrapper
1018 public function dropTable( $tableName, $fName = __METHOD__
) {
1019 if ( !$this->tableExists( $tableName, $fName ) ) {
1023 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1029 protected function getDefaultSchemaVars() {
1030 $vars = parent
::getDefaultSchemaVars();
1031 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1032 $vars['wgDBTableOptions'] = str_replace(
1035 $vars['wgDBTableOptions']
1042 * Get status information from SHOW STATUS in an associative array
1044 * @param $which string
1047 function getMysqlStatus( $which = "%" ) {
1048 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1051 foreach ( $res as $row ) {
1052 $status[$row->Variable_name
] = $row->Value
;
1059 * Lists VIEWs in the database
1061 * @param string $prefix Only show VIEWs with this prefix, eg.
1062 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1063 * @param string $fname Name of calling function
1067 public function listViews( $prefix = null, $fname = __METHOD__
) {
1069 if ( !isset( $this->allViews
) ) {
1071 // The name of the column containing the name of the VIEW
1072 $propertyName = 'Tables_in_' . $this->mDBname
;
1074 // Query for the VIEWS
1075 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1076 $this->allViews
= array();
1077 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1078 array_push( $this->allViews
, $row[$propertyName] );
1082 if ( is_null( $prefix ) ||
$prefix === '' ) {
1083 return $this->allViews
;
1086 $filteredViews = array();
1087 foreach ( $this->allViews
as $viewName ) {
1088 // Does the name of this VIEW start with the table-prefix?
1089 if ( strpos( $viewName, $prefix ) === 0 ) {
1090 array_push( $filteredViews, $viewName );
1094 return $filteredViews;
1098 * Differentiates between a TABLE and a VIEW.
1100 * @param $name string: Name of the TABLE/VIEW to test
1104 public function isView( $name, $prefix = null ) {
1105 return in_array( $name, $this->listViews( $prefix ) );
1113 class MySQLField
implements Field
{
1114 private $name, $tablename, $default, $max_length, $nullable,
1115 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1117 function __construct( $info ) {
1118 $this->name
= $info->name
;
1119 $this->tablename
= $info->table
;
1120 $this->default = $info->def
;
1121 $this->max_length
= $info->max_length
;
1122 $this->nullable
= !$info->not_null
;
1123 $this->is_pk
= $info->primary_key
;
1124 $this->is_unique
= $info->unique_key
;
1125 $this->is_multiple
= $info->multiple_key
;
1126 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1127 $this->type
= $info->type
;
1128 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1141 function tableName() {
1142 return $this->tableName
;
1155 function isNullable() {
1156 return $this->nullable
;
1159 function defaultValue() {
1160 return $this->default;
1167 return $this->is_key
;
1173 function isMultipleKey() {
1174 return $this->is_multiple
;
1177 function isBinary() {
1178 return $this->binary
;
1182 class MySQLMasterPos
implements DBMasterPos
{
1185 function __construct( $file, $pos ) {
1186 $this->file
= $file;
1190 function __toString() {
1191 // e.g db1034-bin.000976/843431247
1192 return "{$this->file}/{$this->pos}";
1196 * @return array|false (int, int)
1198 protected function getCoordinates() {
1200 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1201 return array( (int)$m[1], (int)$m[2] );
1207 function hasReached( MySQLMasterPos
$pos ) {
1208 $thisPos = $this->getCoordinates();
1209 $thatPos = $pos->getCoordinates();
1211 return ( $thisPos && $thatPos && $thisPos >= $thatPos );