databasepostgres.php

来自「php 开发的内容管理系统」· PHP 代码 · 共 610 行 · 第 1/2 页

PHP
610
字号
<?php/** * This is PostgreSQL database abstraction layer. * * As it includes more generic version for DB functions, * than MySQL ones, some of them should be moved to parent * Database class. * * @package MediaWiki *//** * Depends on database */require_once( 'Database.php' );class DatabasePostgres extends Database {	var $mInsertId = NULL;	var $mLastResult = NULL;	function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,		$failFunction = false, $flags = 0 )	{		global $wgOut, $wgDBprefix, $wgCommandLineMode;		# Can't get a reference if it hasn't been set yet		if ( !isset( $wgOut ) ) {			$wgOut = NULL;		}		$this->mOut =& $wgOut;		$this->mFailFunction = $failFunction;		$this->mFlags = $flags;		$this->open( $server, $user, $password, $dbName);	}	static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,		$failFunction = false, $flags = 0)	{		return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );	}	/**	 * Usually aborts on failure	 * If the failFunction is set to a non-zero integer, returns success	 */	function open( $server, $user, $password, $dbName ) {		# Test for PostgreSQL support, to avoid suppressed fatal error		if ( !function_exists( 'pg_connect' ) ) {			throw new DBConnectionError( $this, "PostgreSQL functions missing, have you compiled PHP with the --with-pgsql option?\n" );		}		global $wgDBport;		$this->close();		$this->mServer = $server;		$port = $wgDBport;		$this->mUser = $user;		$this->mPassword = $password;		$this->mDBname = $dbName;		$success = false;		$hstring="";		if ($server!=false && $server!="") {			$hstring="host=$server ";		}		if ($port!=false && $port!="") {			$hstring .= "port=$port ";		}		error_reporting( E_ALL );		@$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");		if ( $this->mConn == false ) {			wfDebug( "DB connection error\n" );			wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );			wfDebug( $this->lastError()."\n" );			return false;		}		$this->mOpened = true;		## If this is the initial connection, setup the schema stuff		if (defined('MEDIAWIKI_INSTALL') and !defined('POSTGRES_SEARCHPATH')) {			global $wgDBmwschema, $wgDBts2schema, $wgDBname;			## Do we have the basic tsearch2 table?			print "<li>Checking for tsearch2 ...";			if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {				print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";				print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";				print " for instructions.</li>\n";				dieout("</ul>");			}							print "OK</li>\n";			## Do we have plpgsql installed?			print "<li>Checking for plpgsql ...";			$SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";			$res = $this->doQuery($SQL);			$rows = $this->numRows($this->doQuery($SQL));			if ($rows < 1) {				print "<b>FAILED</b>. Make sure the language plpgsql is installed for the database <tt>$wgDBname</tt>t</li>";				## XXX Better help				dieout("</ul>");			}			print "OK</li>\n";			## Does the schema already exist? Who owns it?			$result = $this->schemaExists($wgDBmwschema);			if (!$result) {				print "<li>Creating schema <b>$wgDBmwschema</b> ...";				$result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");				if (!$result) {					print "FAILED.</li>\n";					return false;				}				print "ok</li>\n";			}			else if ($result != $user) {				print "<li>Schema <b>$wgDBmwschema</b> exists but is not owned by <b>$user</b>. Not ideal.</li>\n";			}			else {				print "<li>Schema <b>$wgDBmwschema</b> exists and is owned by <b>$user ($result)</b>. Excellent.</li>\n";			}			## Fix up the search paths if needed			print "<li>Setting the search path for user <b>$user</b> ...";			$path = "$wgDBmwschema";			if ($wgDBts2schema !== $wgDBmwschema)				$path .= ", $wgDBts2schema";			if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')				$path .= ", public";			$SQL = "ALTER USER $user SET search_path = $path";			$result = pg_query($this->mConn, $SQL);			if (!$result) {				print "FAILED.</li>\n";				return false;			}			print "ok</li>\n";			## Set for the rest of this session			$SQL = "SET search_path = $path";			$result = pg_query($this->mConn, $SQL);			if (!$result) {				print "<li>Failed to set search_path</li>\n";				return false;			}			define( "POSTGRES_SEARCHPATH", $path );		}		return $this->mConn;	}	/**	 * Closes a database connection, if it is open	 * Returns success, true if already closed	 */	function close() {		$this->mOpened = false;		if ( $this->mConn ) {			return pg_close( $this->mConn );		} else {			return true;		}	}	function doQuery( $sql ) {		return $this->mLastResult=pg_query( $this->mConn , $sql);	}	function queryIgnore( $sql, $fname = '' ) {		return $this->query( $sql, $fname, true );	}	function freeResult( $res ) {		if ( !@pg_free_result( $res ) ) {			throw new DBUnexpectedError($this,  "Unable to free PostgreSQL result\n" );		}	}	function fetchObject( $res ) {		@$row = pg_fetch_object( $res );		# FIXME: HACK HACK HACK HACK debug		# TODO:		# hashar : not sure if the following test really trigger if the object		#          fetching failled.		if( pg_last_error($this->mConn) ) {			throw new DBUnexpectedError($this,  'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );		}		return $row;	}	function fetchRow( $res ) {		@$row = pg_fetch_array( $res );		if( pg_last_error($this->mConn) ) {			throw new DBUnexpectedError($this,  'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );		}		return $row;	}	function numRows( $res ) {		@$n = pg_num_rows( $res );		if( pg_last_error($this->mConn) ) {			throw new DBUnexpectedError($this,  'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );		}		return $n;	}	function numFields( $res ) { return pg_num_fields( $res ); }	function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }	/**	 * This must be called after nextSequenceVal	 */	function insertId() {		return $this->mInsertId;	}	function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }	function lastError() {		if ( $this->mConn ) {			return pg_last_error();		}		else {			return "No database connection";		}	}	function lastErrno() { return 1; }	function affectedRows() {		return pg_affected_rows( $this->mLastResult );	}	/**	 * Returns information about an index	 * If errors are explicitly ignored, returns NULL on failure	 */	function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {		$sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";		$res = $this->query( $sql, $fname );		if ( !$res ) {			return NULL;		}		while ( $row = $this->fetchObject( $res ) ) {			if ( $row->indexname == $index ) {				return $row;			}		}		return false;	}	function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {		$sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".			" AND indexdef LIKE 'CREATE UNIQUE%({$index})'";		$res = $this->query( $sql, $fname );		if ( !$res )			return NULL;		while ($row = $this->fetchObject( $res ))			return true;		return false;	}	function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {		# PostgreSQL doesn't support options		# We have a go at faking one of them		# TODO: DELAYED, LOW_PRIORITY		if ( !is_array($options))			$options = array($options);		if ( in_array( 'IGNORE', $options ) )			$oldIgnore = $this->ignoreErrors( true );		# IGNORE is performed using single-row inserts, ignoring errors in each		# FIXME: need some way to distiguish between key collision and other types of error		$oldIgnore = $this->ignoreErrors( true );		if ( !is_array( reset( $a ) ) ) {			$a = array( $a );		}		foreach ( $a as $row ) {			parent::insert( $table, $row, $fname, array() );		}		$this->ignoreErrors( $oldIgnore );		$retVal = true;		if ( in_array( 'IGNORE', $options ) )			$this->ignoreErrors( $oldIgnore );		return $retVal;	}	function tableName( $name ) {		# Replace backticks into double quotes		$name = strtr($name,'`','"');		# Now quote PG reserved keywords		switch( $name ) {			case 'user':			case 'old':			case 'group':

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?