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 return $this->reportConnectionError( "Error setting sql_mode to $mode" );
134 $this->mOpened
= true;
135 wfProfileOut( __METHOD__
);
141 * Open a connection to a MySQL server
143 * @param $realServer string
144 * @return mixed Raw connection
145 * @throws DBConnectionError
147 abstract protected function mysqlConnect( $realServer );
150 * Set the character set of the MySQL link
152 * @param string $charset
155 abstract protected function mysqlSetCharset( $charset );
158 * @param $res ResultWrapper
159 * @throws DBUnexpectedError
161 function freeResult( $res ) {
162 if ( $res instanceof ResultWrapper
) {
165 wfSuppressWarnings();
166 $ok = $this->mysqlFreeResult( $res );
169 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
176 * @param $res Raw result
179 abstract protected function mysqlFreeResult( $res );
182 * @param $res ResultWrapper
183 * @return object|bool
184 * @throws DBUnexpectedError
186 function fetchObject( $res ) {
187 if ( $res instanceof ResultWrapper
) {
190 wfSuppressWarnings();
191 $row = $this->mysqlFetchObject( $res );
194 $errno = $this->lastErrno();
195 // Unfortunately, mysql_fetch_object does not reset the last errno.
196 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
197 // these are the only errors mysql_fetch_object can cause.
198 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
199 if ( $errno == 2000 ||
$errno == 2013 ) {
200 throw new DBUnexpectedError(
202 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() )
210 * Fetch a result row as an object
212 * @param $res Raw result
215 abstract protected function mysqlFetchObject( $res );
218 * @param $res ResultWrapper
220 * @throws DBUnexpectedError
222 function fetchRow( $res ) {
223 if ( $res instanceof ResultWrapper
) {
226 wfSuppressWarnings();
227 $row = $this->mysqlFetchArray( $res );
230 $errno = $this->lastErrno();
231 // Unfortunately, mysql_fetch_array does not reset the last errno.
232 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
233 // these are the only errors mysql_fetch_array can cause.
234 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
235 if ( $errno == 2000 ||
$errno == 2013 ) {
236 throw new DBUnexpectedError(
238 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() )
246 * Fetch a result row as an associative and numeric array
248 * @param $res Raw result
251 abstract protected function mysqlFetchArray( $res );
254 * @throws DBUnexpectedError
255 * @param $res ResultWrapper
258 function numRows( $res ) {
259 if ( $res instanceof ResultWrapper
) {
262 wfSuppressWarnings();
263 $n = $this->mysqlNumRows( $res );
266 // Unfortunately, mysql_num_rows does not reset the last errno.
267 // We are not checking for any errors here, since
268 // these are no errors mysql_num_rows can cause.
269 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
270 // See https://bugzilla.wikimedia.org/42430
275 * Get number of rows in result
277 * @param $res Raw result
280 abstract protected function mysqlNumRows( $res );
283 * @param $res ResultWrapper
286 function numFields( $res ) {
287 if ( $res instanceof ResultWrapper
) {
291 return $this->mysqlNumFields( $res );
295 * Get number of fields in result
297 * @param $res Raw result
300 abstract protected function mysqlNumFields( $res );
303 * @param $res ResultWrapper
307 function fieldName( $res, $n ) {
308 if ( $res instanceof ResultWrapper
) {
312 return $this->mysqlFieldName( $res, $n );
316 * Get the name of the specified field in a result
318 * @param $res Raw result
322 abstract protected function mysqlFieldName( $res, $n );
325 * @param $res ResultWrapper
329 function dataSeek( $res, $row ) {
330 if ( $res instanceof ResultWrapper
) {
334 return $this->mysqlDataSeek( $res, $row );
338 * Move internal result pointer
340 * @param $res Raw result
344 abstract protected function mysqlDataSeek( $res, $row );
349 function lastError() {
350 if ( $this->mConn
) {
351 # Even if it's non-zero, it can still be invalid
352 wfSuppressWarnings();
353 $error = $this->mysqlError( $this->mConn
);
355 $error = $this->mysqlError();
359 $error = $this->mysqlError();
362 $error .= ' (' . $this->mServer
. ')';
369 * Returns the text of the error message from previous MySQL operation
371 * @param $conn Raw connection
374 abstract protected function mysqlError( $conn = null );
377 * @param $table string
378 * @param $uniqueIndexes
380 * @param $fname string
381 * @return ResultWrapper
383 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
384 return $this->nativeReplace( $table, $rows, $fname );
388 * Estimate rows in dataset
389 * Returns estimated count, based on EXPLAIN output
390 * Takes same arguments as Database::select()
392 * @param $table string|array
393 * @param $vars string|array
394 * @param $conds string|array
395 * @param $fname string
396 * @param $options string|array
399 public function estimateRowCount( $table, $vars = '*', $conds = '',
400 $fname = __METHOD__
, $options = array()
402 $options['EXPLAIN'] = true;
403 $res = $this->select( $table, $vars, $conds, $fname, $options );
404 if ( $res === false ) {
407 if ( !$this->numRows( $res ) ) {
412 foreach ( $res as $plan ) {
413 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
420 * @param $table string
421 * @param $field string
422 * @return bool|MySQLField
424 function fieldInfo( $table, $field ) {
425 $table = $this->tableName( $table );
426 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
430 $n = $this->mysqlNumFields( $res->result
);
431 for ( $i = 0; $i < $n; $i++
) {
432 $meta = $this->mysqlFetchField( $res->result
, $i );
433 if ( $field == $meta->name
) {
434 return new MySQLField( $meta );
442 * Get column information from a result
444 * @param $res Raw result
448 abstract protected function mysqlFetchField( $res, $n );
451 * Get information about an index into an object
452 * Returns false if the index does not exist
454 * @param $table string
455 * @param $index string
456 * @param $fname string
457 * @return bool|array|null False or null on failure
459 function indexInfo( $table, $index, $fname = __METHOD__
) {
460 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
461 # SHOW INDEX should work for 3.x and up:
462 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
463 $table = $this->tableName( $table );
464 $index = $this->indexName( $index );
466 $sql = 'SHOW INDEX FROM ' . $table;
467 $res = $this->query( $sql, $fname );
475 foreach ( $res as $row ) {
476 if ( $row->Key_name
== $index ) {
481 return empty( $result ) ?
false : $result;
489 function strencode( $s ) {
490 $sQuoted = $this->mysqlRealEscapeString( $s );
492 if ( $sQuoted === false ) {
494 $sQuoted = $this->mysqlRealEscapeString( $s );
501 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
507 public function addIdentifierQuotes( $s ) {
508 // Characters in the range \u0001-\uFFFF are valid in a quoted identifier
509 // Remove NUL bytes and escape backticks by doubling
510 return '`' . str_replace( array( "\0", '`' ), array( '', '``' ), $s ) . '`';
514 * @param $name string
517 public function isQuotedIdentifier( $name ) {
518 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
525 $ping = $this->mysqlPing();
530 $this->closeConnection();
531 $this->mOpened
= false;
532 $this->mConn
= false;
533 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
539 * Ping a server connection or reconnect if there is no connection
543 abstract protected function mysqlPing();
548 * This will do a SHOW SLAVE STATUS
553 if ( !is_null( $this->mFakeSlaveLag
) ) {
554 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
556 return $this->mFakeSlaveLag
;
559 return $this->getLagFromSlaveStatus();
565 function getLagFromSlaveStatus() {
566 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
570 $row = $res->fetchObject();
574 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
577 return intval( $row->Seconds_Behind_Master
);
582 * @deprecated in 1.19, use getLagFromSlaveStatus
586 function getLagFromProcesslist() {
587 wfDeprecated( __METHOD__
, '1.19' );
588 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
592 # Find slave SQL thread
593 foreach ( $res as $row ) {
594 /* This should work for most situations - when default db
595 * for thread is not specified, it had no events executed,
596 * and therefore it doesn't know yet how lagged it is.
598 * Relay log I/O thread does not select databases.
600 if ( $row->User
== 'system user' &&
601 $row->State
!= 'Waiting for master to send event' &&
602 $row->State
!= 'Connecting to master' &&
603 $row->State
!= 'Queueing master event to the relay log' &&
604 $row->State
!= 'Waiting for master update' &&
605 $row->State
!= 'Requesting binlog dump' &&
606 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
607 $row->State
!= 'Reconnecting after a failed master event read' &&
608 $row->State
!= 'Registering slave on master'
610 # This is it, return the time (except -ve)
611 if ( $row->Time
> 0x7fffffff ) {
623 * Wait for the slave to catch up to a given master position.
624 * @TODO: return values for this and base class are rubbish
626 * @param $pos DBMasterPos object
627 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
628 * @return bool|string
630 function masterPosWait( DBMasterPos
$pos, $timeout ) {
631 if ( $this->lastKnownSlavePos
&& $this->lastKnownSlavePos
->hasReached( $pos ) ) {
632 return '0'; // http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html
635 wfProfileIn( __METHOD__
);
636 # Commit any open transactions
637 $this->commit( __METHOD__
, 'flush' );
639 if ( !is_null( $this->mFakeSlaveLag
) ) {
640 $status = parent
::masterPosWait( $pos, $timeout );
641 wfProfileOut( __METHOD__
);
646 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
647 $encFile = $this->addQuotes( $pos->file
);
648 $encPos = intval( $pos->pos
);
649 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
650 $res = $this->doQuery( $sql );
653 if ( $res && $row = $this->fetchRow( $res ) ) {
654 $status = $row[0]; // can be NULL, -1, or 0+ per the MySQL manual
655 if ( ctype_digit( $status ) ) { // success
656 $this->lastKnownSlavePos
= $pos;
660 wfProfileOut( __METHOD__
);
666 * Get the position of the master from SHOW SLAVE STATUS
668 * @return MySQLMasterPos|bool
670 function getSlavePos() {
671 if ( !is_null( $this->mFakeSlaveLag
) ) {
672 return parent
::getSlavePos();
675 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
676 $row = $this->fetchObject( $res );
679 $pos = isset( $row->Exec_master_log_pos
)
680 ?
$row->Exec_master_log_pos
681 : $row->Exec_Master_Log_Pos
;
683 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
690 * Get the position of the master from SHOW MASTER STATUS
692 * @return MySQLMasterPos|bool
694 function getMasterPos() {
695 if ( $this->mFakeMaster
) {
696 return parent
::getMasterPos();
699 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
700 $row = $this->fetchObject( $res );
703 return new MySQLMasterPos( $row->File
, $row->Position
);
713 function useIndexClause( $index ) {
714 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
720 function lowPriorityOption() {
721 return 'LOW_PRIORITY';
727 public function getSoftwareLink() {
728 return '[http://www.mysql.com/ MySQL]';
732 * @param $options array
734 public function setSessionOptions( array $options ) {
735 if ( isset( $options['connTimeout'] ) ) {
736 $timeout = (int)$options['connTimeout'];
737 $this->query( "SET net_read_timeout=$timeout" );
738 $this->query( "SET net_write_timeout=$timeout" );
742 public function streamStatementEnd( &$sql, &$newLine ) {
743 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
744 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
745 $this->delimiter
= $m[1];
749 return parent
::streamStatementEnd( $sql, $newLine );
753 * Check to see if a named lock is available. This is non-blocking.
755 * @param string $lockName name of lock to poll
756 * @param string $method name of method calling us
760 public function lockIsFree( $lockName, $method ) {
761 $lockName = $this->addQuotes( $lockName );
762 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
763 $row = $this->fetchObject( $result );
765 return ( $row->lockstatus
== 1 );
769 * @param $lockName string
770 * @param $method string
771 * @param $timeout int
774 public function lock( $lockName, $method, $timeout = 5 ) {
775 $lockName = $this->addQuotes( $lockName );
776 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
777 $row = $this->fetchObject( $result );
779 if ( $row->lockstatus
== 1 ) {
782 wfDebug( __METHOD__
. " failed to acquire lock\n" );
790 * http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
791 * @param $lockName string
792 * @param $method string
795 public function unlock( $lockName, $method ) {
796 $lockName = $this->addQuotes( $lockName );
797 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
798 $row = $this->fetchObject( $result );
800 return ( $row->lockstatus
== 1 );
805 * @param $write array
806 * @param $method string
807 * @param $lowPriority bool
810 public function lockTables( $read, $write, $method, $lowPriority = true ) {
813 foreach ( $write as $table ) {
814 $tbl = $this->tableName( $table ) .
815 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
819 foreach ( $read as $table ) {
820 $items[] = $this->tableName( $table ) . ' READ';
822 $sql = "LOCK TABLES " . implode( ',', $items );
823 $this->query( $sql, $method );
829 * @param $method string
832 public function unlockTables( $method ) {
833 $this->query( "UNLOCK TABLES", $method );
839 * Get search engine class. All subclasses of this
840 * need to implement this if they wish to use searching.
844 public function getSearchEngine() {
845 return 'SearchMySQL';
852 public function setBigSelects( $value = true ) {
853 if ( $value === 'default' ) {
854 if ( $this->mDefaultBigSelects
=== null ) {
855 # Function hasn't been called before so it must already be set to the default
858 $value = $this->mDefaultBigSelects
;
860 } elseif ( $this->mDefaultBigSelects
=== null ) {
861 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
863 $encValue = $value ?
'1' : '0';
864 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
868 * DELETE where the condition is a join. MySql uses multi-table deletes.
869 * @param $delTable string
870 * @param $joinTable string
871 * @param $delVar string
872 * @param $joinVar string
873 * @param $conds array|string
874 * @param bool|string $fname bool
875 * @throws DBUnexpectedError
876 * @return bool|ResultWrapper
878 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
880 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
883 $delTable = $this->tableName( $delTable );
884 $joinTable = $this->tableName( $joinTable );
885 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
887 if ( $conds != '*' ) {
888 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
891 return $this->query( $sql, $fname );
895 * @param string $table
897 * @param array $uniqueIndexes
899 * @param string $fname
900 * @param array $options
903 public function upsert(
904 $table, array $rows, array $uniqueIndexes, array $set, $fname = __METHOD__
906 if ( !count( $rows ) ) {
907 return true; // nothing to do
909 $rows = is_array( reset( $rows ) ) ?
$rows : array( $rows );
911 $table = $this->tableName( $table );
912 $columns = array_keys( $rows[0] );
914 $sql = "INSERT INTO $table (" . implode( ',', $columns ) . ') VALUES ';
915 $rowTuples = array();
916 foreach ( $rows as $row ) {
917 $rowTuples[] = '(' . $this->makeList( $row ) . ')';
919 $sql .= implode( ',', $rowTuples );
920 $sql .= " ON DUPLICATE KEY UPDATE " . $this->makeList( $set, LIST_SET
);
922 return (bool)$this->query( $sql, $fname );
926 * Determines how long the server has been up
930 function getServerUptime() {
931 $vars = $this->getMysqlStatus( 'Uptime' );
933 return (int)$vars['Uptime'];
937 * Determines if the last failure was due to a deadlock
941 function wasDeadlock() {
942 return $this->lastErrno() == 1213;
946 * Determines if the last failure was due to a lock timeout
950 function wasLockTimeout() {
951 return $this->lastErrno() == 1205;
955 * Determines if the last query error was something that should be dealt
956 * with by pinging the connection and reissuing the query
960 function wasErrorReissuable() {
961 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
965 * Determines if the last failure was due to the database being read-only.
969 function wasReadOnlyError() {
970 return $this->lastErrno() == 1223 ||
971 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
977 * @param $temporary bool
978 * @param $fname string
980 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
981 $tmp = $temporary ?
'TEMPORARY ' : '';
982 $newName = $this->addIdentifierQuotes( $newName );
983 $oldName = $this->addIdentifierQuotes( $oldName );
984 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
985 $this->query( $query, $fname );
989 * List all tables on the database
991 * @param string $prefix Only show tables with this prefix, e.g. mw_
992 * @param string $fname calling function name
995 function listTables( $prefix = null, $fname = __METHOD__
) {
996 $result = $this->query( "SHOW TABLES", $fname );
1000 foreach ( $result as $table ) {
1001 $vars = get_object_vars( $table );
1002 $table = array_pop( $vars );
1004 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1005 $endArray[] = $table;
1014 * @param $fName string
1015 * @return bool|ResultWrapper
1017 public function dropTable( $tableName, $fName = __METHOD__
) {
1018 if ( !$this->tableExists( $tableName, $fName ) ) {
1022 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
1028 protected function getDefaultSchemaVars() {
1029 $vars = parent
::getDefaultSchemaVars();
1030 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
1031 $vars['wgDBTableOptions'] = str_replace(
1034 $vars['wgDBTableOptions']
1041 * Get status information from SHOW STATUS in an associative array
1043 * @param $which string
1046 function getMysqlStatus( $which = "%" ) {
1047 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1050 foreach ( $res as $row ) {
1051 $status[$row->Variable_name
] = $row->Value
;
1058 * Lists VIEWs in the database
1060 * @param string $prefix Only show VIEWs with this prefix, eg.
1061 * unit_test_, or $wgDBprefix. Default: null, would return all views.
1062 * @param string $fname Name of calling function
1066 public function listViews( $prefix = null, $fname = __METHOD__
) {
1068 if ( !isset( $this->allViews
) ) {
1070 // The name of the column containing the name of the VIEW
1071 $propertyName = 'Tables_in_' . $this->mDBname
;
1073 // Query for the VIEWS
1074 $result = $this->query( 'SHOW FULL TABLES WHERE TABLE_TYPE = "VIEW"' );
1075 $this->allViews
= array();
1076 while ( ( $row = $this->fetchRow( $result ) ) !== false ) {
1077 array_push( $this->allViews
, $row[$propertyName] );
1081 if ( is_null( $prefix ) ||
$prefix === '' ) {
1082 return $this->allViews
;
1085 $filteredViews = array();
1086 foreach ( $this->allViews
as $viewName ) {
1087 // Does the name of this VIEW start with the table-prefix?
1088 if ( strpos( $viewName, $prefix ) === 0 ) {
1089 array_push( $filteredViews, $viewName );
1093 return $filteredViews;
1097 * Differentiates between a TABLE and a VIEW.
1099 * @param $name string: Name of the TABLE/VIEW to test
1103 public function isView( $name, $prefix = null ) {
1104 return in_array( $name, $this->listViews( $prefix ) );
1112 class MySQLField
implements Field
{
1113 private $name, $tablename, $default, $max_length, $nullable,
1114 $is_pk, $is_unique, $is_multiple, $is_key, $type, $binary;
1116 function __construct( $info ) {
1117 $this->name
= $info->name
;
1118 $this->tablename
= $info->table
;
1119 $this->default = $info->def
;
1120 $this->max_length
= $info->max_length
;
1121 $this->nullable
= !$info->not_null
;
1122 $this->is_pk
= $info->primary_key
;
1123 $this->is_unique
= $info->unique_key
;
1124 $this->is_multiple
= $info->multiple_key
;
1125 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
1126 $this->type
= $info->type
;
1127 $this->binary
= isset( $info->binary
) ?
$info->binary
: false;
1140 function tableName() {
1141 return $this->tableName
;
1154 function isNullable() {
1155 return $this->nullable
;
1158 function defaultValue() {
1159 return $this->default;
1166 return $this->is_key
;
1172 function isMultipleKey() {
1173 return $this->is_multiple
;
1176 function isBinary() {
1177 return $this->binary
;
1181 class MySQLMasterPos
implements DBMasterPos
{
1184 function __construct( $file, $pos ) {
1185 $this->file
= $file;
1189 function __toString() {
1190 // e.g db1034-bin.000976/843431247
1191 return "{$this->file}/{$this->pos}";
1195 * @return array|false (int, int)
1197 protected function getCoordinates() {
1199 if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
1200 return array( (int)$m[1], (int)$m[2] );
1206 function hasReached( MySQLMasterPos
$pos ) {
1207 $thisPos = $this->getCoordinates();
1208 $thatPos = $pos->getCoordinates();
1210 return ( $thisPos && $thatPos && $thisPos >= $thatPos );