1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132 |
- <?php
- require_once 'common.php';
- class DB_pgsql extends DB_common
- {
-
-
- public $phptype = 'pgsql';
-
- public $dbsyntax = 'pgsql';
-
- public $features = array(
- 'limit' => 'alter',
- 'new_link' => '4.3.0',
- 'numrows' => true,
- 'pconnect' => true,
- 'prepare' => false,
- 'ssl' => true,
- 'transactions' => true,
- );
-
- public $errorcode_map = array();
-
- public $connection;
-
- public $dsn = array();
-
- public $autocommit = true;
-
- public $transaction_opcount = 0;
-
- public $affected = 0;
-
- public $row = array();
-
- public $_num_rows = array();
-
-
-
- public function __construct()
- {
- parent::__construct();
- }
-
-
-
- public function connect($dsn, $persistent = false)
- {
- if (!PEAR::loadExtension('pgsql')) {
- return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
- }
- $this->dsn = $dsn;
- if ($dsn['dbsyntax']) {
- $this->dbsyntax = $dsn['dbsyntax'];
- }
- $protocol = $dsn['protocol'] ? $dsn['protocol'] : 'tcp';
- $params = array('');
- if ($protocol == 'tcp') {
- if ($dsn['hostspec']) {
- $params[0] .= 'host=' . $dsn['hostspec'];
- }
- if ($dsn['port']) {
- $params[0] .= ' port=' . $dsn['port'];
- }
- } elseif ($protocol == 'unix') {
-
- if ($dsn['socket']) {
- $params[0] .= 'host=' . $dsn['socket'];
- }
- if ($dsn['port']) {
- $params[0] .= ' port=' . $dsn['port'];
- }
- }
- if ($dsn['database']) {
- $params[0] .= ' dbname=\'' . addslashes($dsn['database']) . '\'';
- }
- if ($dsn['username']) {
- $params[0] .= ' user=\'' . addslashes($dsn['username']) . '\'';
- }
- if ($dsn['password']) {
- $params[0] .= ' password=\'' . addslashes($dsn['password']) . '\'';
- }
- if (!empty($dsn['options'])) {
- $params[0] .= ' options=' . $dsn['options'];
- }
- if (!empty($dsn['tty'])) {
- $params[0] .= ' tty=' . $dsn['tty'];
- }
- if (!empty($dsn['connect_timeout'])) {
- $params[0] .= ' connect_timeout=' . $dsn['connect_timeout'];
- }
- if (!empty($dsn['sslmode'])) {
- $params[0] .= ' sslmode=' . $dsn['sslmode'];
- }
- if (!empty($dsn['service'])) {
- $params[0] .= ' service=' . $dsn['service'];
- }
- if (isset($dsn['new_link'])
- && ($dsn['new_link'] == 'true' || $dsn['new_link'] === true)) {
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = PGSQL_CONNECT_FORCE_NEW;
- }
- }
- $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
- $ini = ini_get('track_errors');
- $php_errormsg = '';
- if ($ini) {
- $this->connection = @call_user_func_array(
- $connect_function,
- $params
- );
- } else {
- @ini_set('track_errors', 1);
- $this->connection = @call_user_func_array(
- $connect_function,
- $params
- );
- @ini_set('track_errors', $ini);
- }
- if (!$this->connection) {
- return $this->raiseError(
- DB_ERROR_CONNECT_FAILED,
- null,
- null,
- null,
- $php_errormsg
- );
- }
- return DB_OK;
- }
-
-
-
- public function disconnect()
- {
- $ret = @pg_close($this->connection);
- $this->connection = null;
- return $ret;
- }
-
-
-
- public function simpleQuery($query)
- {
- $ismanip = $this->_checkManip($query);
- $this->last_query = $query;
- $query = $this->modifyQuery($query);
- if (!$this->autocommit && $ismanip) {
- if ($this->transaction_opcount == 0) {
- $result = @pg_query($this->connection, 'begin;');
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
- }
- $this->transaction_opcount++;
- }
- $result = @pg_query($this->connection, $query);
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
-
- if ($ismanip) {
- $this->affected = @pg_affected_rows($result);
- return DB_OK;
- } elseif (preg_match(
- '/^\s*\(*\s*(SELECT|EXPLAIN|FETCH|SHOW|WITH)\s/si',
- $query
- )) {
- $this->row[(int)$result] = 0;
- $numrows = $this->numRows($result);
- if (is_object($numrows)) {
- return $numrows;
- }
- $this->_num_rows[(int)$result] = $numrows;
- $this->affected = 0;
- return $result;
- } else {
- $this->affected = 0;
- return DB_OK;
- }
- }
-
-
-
- public function _checkManip($query)
- {
- return (preg_match('/^\s*(SAVEPOINT|RELEASE)\s+/i', $query)
- || parent::_checkManip($query));
- }
-
-
-
- public function pgsqlRaiseError($errno = null)
- {
- $native = $this->errorNative();
- if (!$native) {
- $native = 'Database connection has been lost.';
- $errno = DB_ERROR_CONNECT_FAILED;
- }
- if ($errno === null) {
- $errno = $this->errorCode($native);
- }
- return $this->raiseError($errno, null, null, null, $native);
- }
-
-
-
- public function errorNative()
- {
- return @pg_errormessage($this->connection);
- }
-
-
-
- public function errorCode($errormsg)
- {
- static $error_regexps;
- if (!isset($error_regexps)) {
- $error_regexps = array(
- '/column .* (of relation .*)?does not exist/i'
- => DB_ERROR_NOSUCHFIELD,
- '/(relation|sequence|table).*does not exist|class .* not found/i'
- => DB_ERROR_NOSUCHTABLE,
- '/index .* does not exist/'
- => DB_ERROR_NOT_FOUND,
- '/relation .* already exists/i'
- => DB_ERROR_ALREADY_EXISTS,
- '/(divide|division) by zero$/i'
- => DB_ERROR_DIVZERO,
- '/pg_atoi: error in .*: can\'t parse /i'
- => DB_ERROR_INVALID_NUMBER,
- '/invalid input syntax for( type)? (integer|numeric)/i'
- => DB_ERROR_INVALID_NUMBER,
- '/value .* is out of range for type \w*int/i'
- => DB_ERROR_INVALID_NUMBER,
- '/integer out of range/i'
- => DB_ERROR_INVALID_NUMBER,
- '/value too long for type character/i'
- => DB_ERROR_INVALID,
- '/attribute .* not found|relation .* does not have attribute/i'
- => DB_ERROR_NOSUCHFIELD,
- '/column .* specified in USING clause does not exist in (left|right) table/i'
- => DB_ERROR_NOSUCHFIELD,
- '/parser: parse error at or near/i'
- => DB_ERROR_SYNTAX,
- '/syntax error at/'
- => DB_ERROR_SYNTAX,
- '/column reference .* is ambiguous/i'
- => DB_ERROR_SYNTAX,
- '/permission denied/'
- => DB_ERROR_ACCESS_VIOLATION,
- '/violates not-null constraint/'
- => DB_ERROR_CONSTRAINT_NOT_NULL,
- '/violates [\w ]+ constraint/'
- => DB_ERROR_CONSTRAINT,
- '/referential integrity violation/'
- => DB_ERROR_CONSTRAINT,
- '/more expressions than target columns/i'
- => DB_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $errormsg)) {
- return $code;
- }
- }
-
- return DB_ERROR;
- }
-
-
-
- public function numRows($result)
- {
- $rows = @pg_numrows($result);
- if ($rows === null) {
- return $this->pgsqlRaiseError();
- }
- return $rows;
- }
-
-
-
- public function nextResult($result)
- {
- return false;
- }
-
-
-
- public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
- {
- $result_int = (int)$result;
- $rownum = ($rownum !== null) ? $rownum : $this->row[$result_int];
- if ($rownum >= $this->_num_rows[$result_int]) {
- return null;
- }
- if ($fetchmode & DB_FETCHMODE_ASSOC) {
- $arr = @pg_fetch_array($result, $rownum, PGSQL_ASSOC);
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
- $arr = array_change_key_case($arr, CASE_LOWER);
- }
- } else {
- $arr = @pg_fetch_row($result, $rownum);
- }
- if (!$arr) {
- return null;
- }
- if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
- $this->_rtrimArrayValues($arr);
- }
- if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
- $this->_convertNullArrayValuesToEmpty($arr);
- }
- $this->row[$result_int] = ++$rownum;
- return DB_OK;
- }
-
-
-
- public function freeResult($result)
- {
- if (is_resource($result)) {
- unset($this->row[(int)$result]);
- unset($this->_num_rows[(int)$result]);
- $this->affected = 0;
- return @pg_freeresult($result);
- }
- return false;
- }
-
-
-
- public function quoteBoolean($boolean)
- {
- return $boolean ? 'TRUE' : 'FALSE';
- }
-
-
-
- public function escapeSimple($str)
- {
- if (function_exists('pg_escape_string')) {
-
- if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
- return pg_escape_string($this->connection, $str);
- } else {
- return pg_escape_string($str);
- }
- } else {
- return str_replace("'", "''", str_replace('\\', '\\\\', $str));
- }
- }
-
-
-
- public function numCols($result)
- {
- $cols = @pg_numfields($result);
- if (!$cols) {
- return $this->pgsqlRaiseError();
- }
- return $cols;
- }
-
-
-
- public function autoCommit($onoff = false)
- {
-
-
- $this->autocommit = $onoff ? true : false;
- return DB_OK;
- }
-
-
-
- public function commit()
- {
- if ($this->transaction_opcount > 0) {
-
-
- $result = @pg_query($this->connection, 'end;');
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
- }
- return DB_OK;
- }
-
-
-
- public function rollback()
- {
- if ($this->transaction_opcount > 0) {
- $result = @pg_query($this->connection, 'abort;');
- $this->transaction_opcount = 0;
- if (!$result) {
- return $this->pgsqlRaiseError();
- }
- }
- return DB_OK;
- }
-
-
-
- public function affectedRows()
- {
- return $this->affected;
- }
-
-
-
- public function nextId($seq_name, $ondemand = true)
- {
- $seqname = $this->getSequenceName($seq_name);
- $repeat = false;
- do {
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->query("SELECT NEXTVAL('${seqname}')");
- $this->popErrorHandling();
- if ($ondemand && DB::isError($result) &&
- $result->getCode() == DB_ERROR_NOSUCHTABLE) {
- $repeat = true;
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $result = $this->createSequence($seq_name);
- $this->popErrorHandling();
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- } else {
- $repeat = false;
- }
- } while ($repeat);
- if (DB::isError($result)) {
- return $this->raiseError($result);
- }
- $arr = $result->fetchRow(DB_FETCHMODE_ORDERED);
- $result->free();
- return $arr[0];
- }
-
-
-
- public function createSequence($seq_name)
- {
- $seqname = $this->getSequenceName($seq_name);
- $result = $this->query("CREATE SEQUENCE ${seqname}");
- return $result;
- }
-
-
-
- public function dropSequence($seq_name)
- {
- return $this->query('DROP SEQUENCE '
- . $this->getSequenceName($seq_name));
- }
-
-
-
- public function modifyLimitQuery($query, $from, $count, $params = array())
- {
- return "$query LIMIT $count OFFSET $from";
- }
-
-
-
- public function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
-
- $id = @pg_query($this->connection, "SELECT * FROM $result LIMIT 0");
- $got_string = true;
- } elseif (isset($result->result)) {
-
- $id = $result->result;
- $got_string = false;
- } else {
-
- $id = $result;
- $got_string = false;
- }
- if (!is_resource($id)) {
- return $this->pgsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
- }
- if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strval';
- }
- $count = @pg_numfields($id);
- $res = array();
- if ($mode) {
- $res['num_fields'] = $count;
- }
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => $got_string ? $case_func($result) : '',
- 'name' => $case_func(@pg_fieldname($id, $i)),
- 'type' => @pg_fieldtype($id, $i),
- 'len' => @pg_fieldsize($id, $i),
- 'flags' => $got_string
- ? $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;
- }
- }
-
- if ($got_string) {
- @pg_freeresult($id);
- }
- return $res;
- }
-
-
-
- public function _pgFieldFlags($resource, $num_field, $table_name)
- {
- $field_name = @pg_fieldname($resource, $num_field);
-
-
- $from = 'pg_attribute f, pg_class tab, pg_type typ';
- if (strpos($table_name, '.') !== false) {
- $from .= ', pg_namespace nsp';
- list($schema, $table) = explode('.', $table_name);
- $tableWhere = "tab.relname = '$table' AND tab.relnamespace = nsp.oid AND nsp.nspname = '$schema'";
- } else {
- $tableWhere = "tab.relname = '$table_name'";
- }
- $result = @pg_query($this->connection, "SELECT f.attnotnull, f.atthasdef
- FROM $from
- WHERE tab.relname = typ.typname
- AND typ.typrelid = f.attrelid
- AND f.attname = '$field_name'
- AND $tableWhere");
- if (@pg_numrows($result) > 0) {
- $row = @pg_fetch_row($result, 0);
- $flags = ($row[0] == 't') ? 'not_null ' : '';
- if ($row[1] == 't') {
- $result = @pg_query($this->connection, "SELECT a.adsrc
- FROM $from, pg_attrdef a
- WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
- AND f.attrelid = a.adrelid AND f.attname = '$field_name'
- AND $tableWhere AND f.attnum = a.adnum");
- $row = @pg_fetch_row($result, 0);
- $num = preg_replace("/'(.*)'::\w+/", "\\1", $row[0]);
- $flags .= 'default_' . rawurlencode($num) . ' ';
- }
- } else {
- $flags = '';
- }
- $result = @pg_query($this->connection, "SELECT i.indisunique, i.indisprimary, i.indkey
- FROM $from, pg_index i
- WHERE tab.relname = typ.typname
- AND typ.typrelid = f.attrelid
- AND f.attrelid = i.indrelid
- AND f.attname = '$field_name'
- AND $tableWhere");
- $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' && $row[1] == 'f') ? 'unique_key ' : '';
- $flags .= ($row[1] == 't') ? 'primary_key ' : '';
- if (count($keys) > 1) {
- $flags .= 'multiple_key ';
- }
- }
- }
- return trim($flags);
- }
-
-
-
- public function getSpecialQuery($type)
- {
- switch ($type) {
- case 'tables':
- return '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_|sql_)'"
- . ' 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_'";
- case 'schema.tables':
- return "SELECT schemaname || '.' || tablename"
- . ' AS "Name"'
- . ' FROM pg_catalog.pg_tables'
- . ' WHERE schemaname NOT IN'
- . " ('pg_catalog', 'information_schema', 'pg_toast')";
- case 'schema.views':
- return "SELECT schemaname || '.' || viewname from pg_views WHERE schemaname"
- . " NOT IN ('information_schema', 'pg_catalog')";
- case 'views':
-
- return 'SELECT viewname from pg_views WHERE schemaname'
- . " NOT IN ('information_schema', 'pg_catalog')";
- case 'users':
-
- return 'SELECT usename FROM pg_user';
- case 'databases':
- return 'SELECT datname FROM pg_database';
- case 'functions':
- case 'procedures':
- return 'SELECT proname FROM pg_proc WHERE proowner <> 1';
- default:
- return null;
- }
- }
- }
|