📄 pgsql.php
字号:
* Get the native error code of the last error (if any) that
* occured on the current connection.
*
* @return int native PostgreSQL error code
*/
function errorNative()
{
return pg_errormessage($this->connection);
}
// }}}
// {{{ autoCommit()
/**
* Enable/disable automatic commits
*/
function autoCommit($onoff = false)
{
// XXX if $this->transaction_opcount > 0, we should probably
// issue a warning here.
$this->autocommit = $onoff ? true : false;
return DB_OK;
}
// }}}
// {{{ commit()
/**
* Commit the current transaction.
*/
function commit()
{
if ($this->transaction_opcount > 0) {
// (disabled) hack to shut up error messages from libpq.a
//@fclose(@fopen("php://stderr", "w"));
$result = @pg_exec($this->connection, "end;");
$this->transaction_opcount = 0;
if (!$result) {
return $this->pgsqlRaiseError();
}
}
return DB_OK;
}
// }}}
// {{{ rollback()
/**
* Roll back (undo) the current transaction.
*/
function rollback()
{
if ($this->transaction_opcount > 0) {
$result = @pg_exec($this->connection, "abort;");
$this->transaction_opcount = 0;
if (!$result) {
return $this->pgsqlRaiseError();
}
}
return DB_OK;
}
// }}}
// {{{ affectedRows()
/**
* Gets the number of rows affected by the last query.
* if the last query was a select, returns 0.
*
* @return int number of rows affected by the last query or DB_ERROR
*/
function affectedRows()
{
return $this->affected;
}
// }}}
// {{{ nextId()
/**
* Get the next value in a sequence.
*
* We are using native PostgreSQL sequences. If a sequence does
* not exist, it will be created, unless $ondemand is false.
*
* @access public
* @param string $seq_name the name of the sequence
* @param bool $ondemand whether to create the sequence on demand
* @return a sequence integer, or a DB error
*/
function nextId($seq_name, $ondemand = true)
{
$sqn = preg_replace('/[^a-z0-9_]/i', '_', $seq_name);
$repeat = 0;
do {
$this->pushErrorHandling(PEAR_ERROR_RETURN);
$result = $this->query("SELECT NEXTVAL('${sqn}_seq')");
$this->popErrorHandling();
if ($ondemand && DB::isError($result) &&
$result->getCode() == DB_ERROR_NOSUCHTABLE) {
$repeat = 1;
$result = $this->createSequence($seq_name);
if (DB::isError($result)) {
return $this->raiseError($result);
}
} else {
$repeat = 0;
}
} while ($repeat);
if (DB::isError($result)) {
return $this->raiseError($result);
}
$arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
$result->free();
return $arr[0];
}
// }}}
// {{{ createSequence()
/**
* Create the sequence
*
* @param string $seq_name the name of the sequence
* @return mixed DB_OK on success or DB error on error
* @access public
*/
function createSequence($seq_name)
{
$sqn = preg_replace('/[^a-z0-9_]/i', '_', $seq_name);
$this->pushErrorHandling(PEAR_ERROR_RETURN);
$result = $this->query("CREATE SEQUENCE ${sqn}_seq");
$this->popErrorHandling();
return $result;
}
// }}}
// {{{ dropSequence()
/**
* Drop a sequence
*
* @param string $seq_name the name of the sequence
* @return mixed DB_OK on success or DB error on error
* @access public
*/
function dropSequence($seq_name)
{
$sqn = preg_replace('/[^a-z0-9_]/i', '_', $seq_name);
return $this->query("DROP SEQUENCE ${sqn}_seq");
}
// }}}
// {{{ modifyLimitQuery()
function modifyLimitQuery($query, $from, $count)
{
$query = $query . " LIMIT $count, $from";
return $query;
}
// }}}
// {{{ pgsqlRaiseError()
function pgsqlRaiseError($errno = null)
{
$native = $this->errorNative();
if ($errno === null) {
$err = $this->errorCode($native);
} else {
$err = $errno;
}
return $this->raiseError($err, null, null, null, $native);
}
// }}}
// {{{ _pgFieldFlags()
/**
* Flags of a Field
*
* @param int $resource PostgreSQL result identifier
* @param int $num_field the field number
*
* @return string The flags of the field ("not_null", "default_xx", "primary_key",
* "unique" and "multiple_key" are supported)
* @access private
*/
function _pgFieldFlags($resource, $num_field, $table_name)
{
$field_name = @pg_fieldname($resource, $num_field);
$result = pg_exec($this->connection, "SELECT f.attnotnull, f.atthasdef
FROM pg_attribute f, pg_class tab, pg_type typ
WHERE tab.relname = typ.typname
AND typ.typrelid = f.attrelid
AND f.attname = '$field_name'
AND tab.relname = '$table_name'");
$row = pg_fetch_row($result, 0);
$flags = ($row[0] == 't') ? 'not_null ' : '';
if ($row[1] == 't') {
$result = pg_exec($this->connection, "SELECT a.adsrc
FROM pg_attribute f, pg_class tab, pg_type typ, pg_attrdef a
WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
AND f.attrelid = a.adrelid AND f.attname = '$field_name'
AND tab.relname = '$table_name'");
$row = pg_fetch_row($result, 0);
$num = str_replace('\'', '', $row[0]);
$flags .= "default_$num ";
}
$result = pg_exec($this->connection, "SELECT i.indisunique, i.indisprimary, i.indkey
FROM pg_attribute f, pg_class tab, pg_type typ, pg_index i
WHERE tab.relname = typ.typname
AND typ.typrelid = f.attrelid
AND f.attrelid = i.indrelid
AND f.attname = '$field_name'
AND tab.relname = '$table_name'");
$count = pg_numrows($result);
for ($i = 0; $i < $count ; $i++) {
$row = pg_fetch_row($result, $i);
$keys = explode(" ", $row[2]);
if (in_array($num_field + 1, $keys)) {
$flags .= ($row[0] == 't') ? 'unique ' : '';
$flags .= ($row[1] == 't') ? 'primary ' : '';
if (count($keys) > 1)
$flags .= 'multiple_key ';
}
}
return trim($flags);
}
// }}}
// {{{ tableInfo()
/**
* Returns information about a table or a result set
*
* NOTE: doesn't support table name and flags if called from a db_result
*
* @param mixed $resource PostgreSQL result identifier or table name
* @param int $mode A valid tableInfo mode (DB_TABLEINFO_ORDERTABLE or
* DB_TABLEINFO_ORDER)
*
* @return array An array with all the information
*/
function tableInfo($result, $mode = null)
{
$count = 0;
$id = 0;
$res = array();
/*
* depending on $mode, metadata returns the following values:
*
* - mode is false (default):
* $result[]:
* [0]["table"] table name
* [0]["name"] field name
* [0]["type"] field type
* [0]["len"] field length
* [0]["flags"] field flags
*
* - mode is DB_TABLEINFO_ORDER
* $result[]:
* ["num_fields"] number of metadata records
* [0]["table"] table name
* [0]["name"] field name
* [0]["type"] field type
* [0]["len"] field length
* [0]["flags"] field flags
* ["order"][field name] index of field named "field name"
* The last one is used, if you have a field name, but no index.
* Test: if (isset($result['meta']['myfield'])) { ...
*
* - mode is DB_TABLEINFO_ORDERTABLE
* the same as above. but additionally
* ["ordertable"][table name][field name] index of field
* named "field name"
*
* this is, because if you have fields from different
* tables with the same field name * they override each
* other with DB_TABLEINFO_ORDER
*
* you can combine DB_TABLEINFO_ORDER and
* DB_TABLEINFO_ORDERTABLE with DB_TABLEINFO_ORDER |
* DB_TABLEINFO_ORDERTABLE * or with DB_TABLEINFO_FULL
*/
// if $result is a string, then we want information about a
// table without a resultset
if (is_string($result)) {
$id = pg_exec($this->connection,"SELECT * FROM $result");
if (empty($id)) {
return $this->pgsqlRaiseError();
}
} else { // else we want information about a resultset
$id = $result;
if (empty($id)) {
return $this->pgsqlRaiseError();
}
}
$count = @pg_numfields($id);
// made this IF due to performance (one if is faster than $count if's)
if (empty($mode)) {
for ($i=0; $i<$count; $i++) {
$res[$i]['table'] = (is_string($result)) ? $result : '';
$res[$i]['name'] = @pg_fieldname ($id, $i);
$res[$i]['type'] = @pg_fieldtype ($id, $i);
$res[$i]['len'] = @pg_fieldsize ($id, $i);
$res[$i]['flags'] = (is_string($result)) ? $this->_pgFieldflags($id, $i, $result) : '';
}
} else { // full
$res["num_fields"]= $count;
for ($i=0; $i<$count; $i++) {
$res[$i]['table'] = (is_string($result)) ? $result : '';
$res[$i]['name'] = @pg_fieldname ($id, $i);
$res[$i]['type'] = @pg_fieldtype ($id, $i);
$res[$i]['len'] = @pg_fieldsize ($id, $i);
$res[$i]['flags'] = (is_string($result)) ? $this->_pgFieldFlags($id, $i, $result) : '';
if ($mode & DB_TABLEINFO_ORDER) {
$res['order'][$res[$i]['name']] = $i;
}
if ($mode & DB_TABLEINFO_ORDERTABLE) {
$res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
}
}
}
// free the result only if we were called on a table
if (is_resource($id)) {
@pg_freeresult($id);
}
return $res;
}
// }}}
// {{{ getTablesQuery()
/**
* Returns the query needed to get some backend info
* @param string $type What kind of info you want to retrieve
* @return string The SQL query string
*/
function getSpecialQuery($type)
{
switch ($type) {
case 'tables': {
$sql = "SELECT c.relname as \"Name\"
FROM pg_class c, pg_user u
WHERE c.relowner = u.usesysid AND c.relkind = 'r'
AND not exists (select 1 from pg_views where viewname = c.relname)
AND c.relname !~ '^pg_'
UNION
SELECT c.relname as \"Name\"
FROM pg_class c
WHERE c.relkind = 'r'
AND not exists (select 1 from pg_views where viewname = c.relname)
AND not exists (select 1 from pg_user where usesysid = c.relowner)
AND c.relname !~ '^pg_'";
break;
}
case 'views': {
// Table cols: viewname | viewowner | definition
$sql = "SELECT viewname FROM pg_views";
break;
}
case 'users': {
// cols: usename |usesysid|usecreatedb|usetrace|usesuper|usecatupd|passwd |valuntil
$sql = 'SELECT usename FROM pg_user';
break;
}
case 'databases': {
$sql = 'SELECT datname FROM pg_database';
break;
}
case 'functions': {
$sql = 'SELECT proname FROM pg_proc';
break;
}
default:
return null;
}
return $sql;
}
// }}}
}
// Local variables:
// tab-width: 4
// c-basic-offset: 4
// End:
?>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -