/** * The function to open a database connection, or return the resource if already open * * @param string $database The name of the database config to use * (Must match the database section name in the conf file) * @return resource|false The PgSQL database resource * or false on failure */ function OA_Dal_Delivery_connect($database = 'database') { // If a connection already exists, then return that if ($database == 'database' && isset($GLOBALS['_MAX']['ADMIN_DB_LINK']) && is_resource($GLOBALS['_MAX']['ADMIN_DB_LINK'])) { return $GLOBALS['_MAX']['ADMIN_DB_LINK']; } elseif ($database == 'rawDatabase' && isset($GLOBALS['_MAX']['RAW_DB_LINK']) && is_resource($GLOBALS['_MAX']['RAW_DB_LINK'])) { return $GLOBALS['_MAX']['RAW_DB_LINK']; } // No connection exists, so create one $conf = $GLOBALS['_MAX']['CONF']; if (!empty($conf[$database])) { $dbConf = $conf[$database]; } else { $dbConf = $conf['database']; } $dbParams = array(); $dbParams[] = 'port=' . (isset($dbConf['port']) ? $dbConf['port'] : 5432); $dbParams[] = !empty($dbConf['protocol']) && $dbConf['protocol'] == 'unix' ? '' : 'host=' . $dbConf['host']; $dbParams[] = empty($dbConf['username']) ? '' : 'user='******'username']; $dbParams[] = empty($dbConf['password']) ? '' : 'password='******'password']; $dbParams[] = 'dbname=' . $dbConf['name']; if ($dbConf['persistent']) { $dbLink = @pg_pconnect(join(' ', $dbParams)); } else { $dbLink = @pg_connect(join(' ', $dbParams)); } if ($dbLink && !empty($conf['databasePgsql']['schema'])) { @pg_query($dbLink, "SET search_path='{$conf['databasePgsql']['schema']}'"); } if ($dbLink && !empty($conf['databaseCharset']['checkComplete']) && !empty($conf['databaseCharset']['clientCharset'])) { @pg_client_encoding($dbLink, $conf['databaseCharset']['clientCharset']); } return $dbLink; }
public static function castLink($link, array $a, Stub $stub, $isNested) { $a['status'] = pg_connection_status($link); $a['status'] = new ConstStub(PGSQL_CONNECTION_OK === $a['status'] ? 'PGSQL_CONNECTION_OK' : 'PGSQL_CONNECTION_BAD', $a['status']); $a['busy'] = pg_connection_busy($link); $a['transaction'] = pg_transaction_status($link); if (isset(self::$transactionStatus[$a['transaction']])) { $a['transaction'] = new ConstStub(self::$transactionStatus[$a['transaction']], $a['transaction']); } $a['pid'] = pg_get_pid($link); $a['last error'] = pg_last_error($link); $a['last notice'] = pg_last_notice($link); $a['host'] = pg_host($link); $a['port'] = pg_port($link); $a['dbname'] = pg_dbname($link); $a['options'] = pg_options($link); $a['version'] = pg_version($link); foreach (self::$paramCodes as $v) { if (false !== ($s = pg_parameter_status($link, $v))) { $a['param'][$v] = $s; } } $a['param']['client_encoding'] = pg_client_encoding($link); $a['param'] = new EnumStub($a['param']); return $a; }
function my_PGSQL_db_connect() { // http://www.php.net/manual/ru/ref.pgsql.php $dblocation = "localhost"; $dbuser = "******"; $dbpassword = ""; $dbname = "bacula"; /*$db = pg_connect("host='$dblocation' dbname='$dbname' user='******' password='******'") or die("[PGSQL]" . pg_last_error());*/ $db = pg_connect("host='{$dblocation}' dbname='{$dbname}' user='******' password='******'") or die("[PGSQL]" . pg_last_error()); pg_set_client_encoding($db, 'SQL_ASCII'); echo "Connect [PGSQL] ", $dbname, ". Encoding ", pg_client_encoding(), ". OK.\n"; return $db; }
function __tcSqlLogEnd($result, $cachedResult = 0) { global $__tcSqlLog, $__tcSqlQueryBeginTime, $__tcSqlLogCount, $__tcPageStartTime; static $client_encoding = ''; $tcSqlQueryEndTime = explode(' ', microtime()); $elapsed = $tcSqlQueryEndTime[1] - $__tcSqlQueryBeginTime[1] + ($tcSqlQueryEndTime[0] - $__tcSqlQueryBeginTime[0]); if (!$client_encoding) { $client_encoding = str_replace('_', '-', pg_client_encoding()); } // if( $client_encoding != 'utf8' && function_exists('iconv') ) { // $__tcSqlLog[$__tcSqlLogCount]['error'] = iconv( $client_encoding, 'utf-8', pg_last_error()); // } // else { $__tcSqlLog[$__tcSqlLogCount]['error'] = pg_last_error(); // } $__tcSqlLog[$__tcSqlLogCount]['errno'] = 0; //mysql_errno(); if ($cachedResult == 0) { $__tcSqlLog[$__tcSqlLogCount]['elapsed'] = ceil($elapsed * 10000) / 10; } else { $__tcSqlLog[$__tcSqlLogCount]['elapsed'] = 0; } $__tcSqlLog[$__tcSqlLogCount]['elapsed'] = sprintf("%4.1f", $__tcSqlLog[$__tcSqlLogCount]['elapsed']); $__tcSqlLog[$__tcSqlLogCount]['cached'] = $cachedResult; $__tcSqlLog[$__tcSqlLogCount]['rows'] = 0; $__tcSqlLog[$__tcSqlLogCount]['endtime'] = $tcSqlQueryEndTime[1] - $__tcPageStartTime[1] + ($tcSqlQueryEndTime[0] - $__tcPageStartTime[0]); $__tcSqlLog[$__tcSqlLogCount]['endtime'] = sprintf("%4.1f", ceil($__tcSqlLog[$__tcSqlLogCount]['endtime'] * 10000) / 10); if (!$cachedResult) { //&& mysql_errno() == 0 ) { switch (strtolower(substr($__tcSqlLog[$__tcSqlLogCount]['sql'], 0, 6))) { case 'select': $__tcSqlLog[$__tcSqlLogCount]['rows'] = pg_num_rows($result); break; case 'insert': case 'delete': case 'update': $__tcSqlLog[$__tcSqlLogCount]['rows'] = pg_affected_rows($result); break; } } $__tcSqlLogCount++; $__tcSqlQueryBeginTime = 0; }
function conn() { //echo $_SERVER['SERVER_NAME']; /*if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { // SSL connection $descriptor = fopen("https://".$_SERVER['SERVER_NAME']."/conexion.conf","r") or sysError("conectaBD.abriendo Archivo de configuracion"); } else{ $descriptor = fopen("http://".$_SERVER['SERVER_NAME']."/conexion.conf","r") or sysError("conectaBD.abriendo Archivo de configuracion"); }*/ $descriptor = fopen("http://localhost/jornadasgvsig/conexion.conf", "r"); $i = 0; while (!feof($descriptor)) { $buffer = fgets($descriptor, 50); if ($i == 0) { $dbname = substr($buffer, 3, -1); } if ($i == 1) { $dbuser = substr($buffer, 3, -1); } if ($i == 2) { $dbuserpass = substr($buffer, 3, -1); } if ($i == 3) { $dbhost = substr($buffer, 3, -1); } if ($i == 4) { $dbport = substr($buffer, 3, -1); } $i++; } $conn = "host={$dbhost} port={$dbport} dbname={$dbname} user={$dbuser} password={$dbuserpass} "; $connDebug = "host={$dbhost} port={$dbport} dbname={$dbname} user={$dbuser} password=xxxxxx "; $conexion = pg_connect($conn) or sysError("conectaBD.pg_connect->{$connDebug}"); $encoding = pg_client_encoding($conexion); pg_set_client_encoding($conexion, "UTF8"); return $conexion; }
public function get_charset() { $r = new stdClass(); $r->charset = pg_client_encoding($this->connection); # pg_parameter_status($this->connection, 'server_encoding') $r->collation = null; $r->comment = 'UTF-8 Unicode'; $r->dir = ''; $r->min_length = 1; $r->max_length = 3; $r->number = 33; $r->state = 993; return $r; }
public static function backup($database, $tables, $filename, $structure = true, $data = true, $drop = true, $compress = true, $full = false) { global $db; $schema = $database; if (!is_array($tables) || empty($tables)) { trigger_error('No tables to backup', E_USER_WARNING); return false; } $crlf = "\n"; $current_user = $db->sql_ufetchrowset('SELECT CURRENT_USER', SQL_NUM); $current_user = $current_user[0][0]; //$search_path = $db->sql_ufetchrowset('SELECT current_schemas(true)'); //$search_path = preg_replace('#^{(.*?)}$#', '\\1', $search_path[0][0]); # doing some DOS-CRLF magic... # this looks better under WinX if (preg_match('#[^(]*\\((.*)\\)[^)]*#', $_SERVER['HTTP_USER_AGENT'], $regs)) { if (false !== stripos($regs[1], 'Win')) { $crlf = "\r\n"; } } if (GZIPSUPPORT) { while (ob_end_clean()) { } header('Content-Encoding: '); } else { $compress = false; } if ($compress) { $filename .= '.gz'; header("Content-Type: application/x-gzip; name=\"{$filename}\""); } else { header("Content-Type: text/x-delimtext; name=\"{$filename}\""); } header("Content-disposition: attachment; filename={$filename}"); $controls = "--{$crlf}-- PostgreSQL dump : {$database}{$crlf}" . "-- " . _ON . " " . formatDateTime(time(), _DATESTRING) . " !{$crlf}--{$crlf}{$crlf}" . "SET client_encoding = '" . pg_client_encoding() . "';{$crlf}" . "SET check_function_bodies = false;{$crlf}" . "SET SESSION AUTHORIZATION '{$current_user}';{$crlf}{$crlf}"; if ($full) { if ($drop) { $controls .= 'DROP SCHEMA ' . $schema . ' CASCADE;' . $crlf; } $controls .= "CREATE SCHEMA {$schema} AUTHORIZATION {$current_user};{$crlf}" . "REVOKE ALL ON SCHEMA {$schema} FROM PUBLIC;{$crlf}" . 'ALTER USER ' . $current_user . ' SET search_path TO ' . $schema . ";{$crlf}" . "{$crlf}"; } DBCtrl::output($controls, $compress); set_time_limit(0); if ($drop && !$full) { SQLCtrl::drop_table_struct($schema, $tables, $crlf, $compress); } if ($structure) { if ($full) { DBCtrl::output(SQLCtrl::get_function($schema, $crlf), $compress); } SQLCtrl::get_table_struct($schema, $tables, $crlf, $compress); } if ($data) { SQLCtrl::get_table_content($schema, $tables, $crlf, false, $compress); } if ($structure) { SQLCtrl::get_index($schema, $tables, $crlf, $compress); DBCtrl::output(SQLCtrl::get_sequence($schema, $tables, $crlf, $full), $compress); } DBCtrl::output($crlf . 'VACUUM ANALYZE;', $compress); if ($compress) { DBCtrl::output('', true, true); } exit; }
public function get_details() { $details = $this->get_versions(); $details['unicode'] = true; $details['character_set_client'] = pg_client_encoding(); return $details; }
/** * Method to get the database connection collation, as reported by the driver. If the connector doesn't support * reporting this value please return an empty string. * * @return string */ public function getConnectionCollation() { return pg_client_encoding($this->connection); }
/** * Connect to db * Must be called before other methods. * @param string $dbhost The database host. * @param string $dbuser The database username. * @param string $dbpass The database username's password. * @param string $dbname The name of the database being connected to. * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used * @param array $dboptions driver specific options * @return bool true * @throws dml_connection_exception if error */ public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions = null) { if ($prefix == '' and !$this->external) { //Enforce prefixes for everybody but mysql throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily()); } $driverstatus = $this->driver_installed(); if ($driverstatus !== true) { throw new dml_exception('dbdriverproblem', $driverstatus); } $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions); $pass = addcslashes($this->dbpass, "'\\"); // Unix socket connections should have lower overhead if (!empty($this->dboptions['dbsocket']) and ($this->dbhost === 'localhost' or $this->dbhost === '127.0.0.1')) { $connection = "user='******' password='******' dbname='{$this->dbname}'"; if (strpos($this->dboptions['dbsocket'], '/') !== false) { // A directory was specified as the socket location. $connection .= " host='" . $this->dboptions['dbsocket'] . "'"; } if (!empty($this->dboptions['dbport'])) { // A port as specified, add it to the connection as it's used as part of the socket path. $connection .= " port ='" . $this->dboptions['dbport'] . "'"; } } else { $this->dboptions['dbsocket'] = ''; if (empty($this->dbname)) { // probably old style socket connection - do not add port $port = ""; } else { if (empty($this->dboptions['dbport'])) { $port = "port ='5432'"; } else { $port = "port ='" . $this->dboptions['dbport'] . "'"; } } $connection = "host='{$this->dbhost}' {$port} user='******' password='******' dbname='{$this->dbname}'"; } if (empty($this->dboptions['dbhandlesoptions'])) { // ALTER USER and ALTER DATABASE are overridden by these settings. $options = array('--client_encoding=utf8', '--standard_conforming_strings=on'); // Select schema if specified, otherwise the first one wins. if (!empty($this->dboptions['dbschema'])) { $options[] = "-c search_path=" . addcslashes($this->dboptions['dbschema'], "'\\"); } $connection .= " options='" . implode(' ', $options) . "'"; } ob_start(); if (empty($this->dboptions['dbpersist'])) { $this->pgsql = pg_connect($connection, PGSQL_CONNECT_FORCE_NEW); } else { $this->pgsql = pg_pconnect($connection, PGSQL_CONNECT_FORCE_NEW); } $dberr = ob_get_contents(); ob_end_clean(); $status = pg_connection_status($this->pgsql); if ($status === false or $status === PGSQL_CONNECTION_BAD) { $this->pgsql = null; throw new dml_connection_exception($dberr); } if (!empty($this->dboptions['dbhandlesoptions'])) { /* We don't trust people who just set the dbhandlesoptions, this code checks up on them. * These functions do not talk to the server, they use the client library knowledge to determine state. */ if (!empty($this->dboptions['dbschema'])) { throw new dml_connection_exception('You cannot specify a schema with dbhandlesoptions, use the database to set it.'); } if (pg_client_encoding($this->pgsql) != 'UTF8') { throw new dml_connection_exception('client_encoding = UTF8 not set, it is: ' . pg_client_encoding($this->pgsql)); } if (pg_escape_string($this->pgsql, '\\') != '\\') { throw new dml_connection_exception('standard_conforming_strings = on, must be set at the database.'); } } // Connection stabilised and configured, going to instantiate the temptables controller $this->temptables = new pgsql_native_moodle_temptables($this); return true; }
public function getAttribute($attribute, &$source = null, $func = 'PDO::getAttribute', &$last_error = null) { switch ($attribute) { case PDO::ATTR_AUTOCOMMIT: return $this->autocommit; break; case PDO::ATTR_CLIENT_VERSION: $ver = pg_version($this->link); return $ver['client']; break; case PDO::ATTR_CONNECTION_STATUS: if (pg_connection_status($this->link) === PGSQL_CONNECTION_OK) { return 'Connection OK; waiting to send.'; } else { return 'Connection BAD'; } break; case PDO::ATTR_SERVER_INFO: return sprintf('PID: %d; Client Encoding: %s; Is Superuser: %s; Session Authorization: %s; Date Style: %s', pg_get_pid($this->link), pg_client_encoding($this->link), pg_parameter_status($this->link, 'is_superuser'), pg_parameter_status($this->link, 'session_authorization'), pg_parameter_status($this->link, 'DateStyle')); break; case PDO::ATTR_SERVER_VERSION: return pg_parameter_status($this->link, 'server_version'); break; default: return parent::getAttribute($attribute, $source, $func, $last_error); break; } }
/** * Opens a connection to the SQL server * * Opens a connection to the SQL server, checking for connection errors, * and performs a ROLLBACK to make sure any old transaction is cleared. * * @param bool $force Whether to force a new connection. * @return bool true on success, false on error * @access public */ public function connect($force = false) { $constr = ''; if (empty($this->_socket)) { if (!empty($this->_hostname)) { $constr .= " host={$this->_hostname}"; } if (!empty($this->_port)) { $constr .= " port={$this->_port}"; } } if (!empty($this->_username)) { $constr .= " user={$this->_username}"; } if (!empty($this->_password)) { $constr .= " password={$this->_password}"; } if (!empty($this->_database)) { $constr .= " dbname={$this->_database}"; } $force = $force === true ? PGSQL_CONNECT_FORCE_NEW : 0; if ($this->_persistent == true) { $this->_connection = pg_pconnect($constr, $force); } else { $this->_connection = pg_connect($constr, $force); } if ($this->_connection === false) { return false; } if (@pg_query($this->_connection, 'ROLLBACK') === false) { return false; } if (function_exists('pg_set_error_verbosity')) { pg_set_error_verbosity($this->_connection, PGSQL_ERRORS_VERBOSE); } // "If libpq is compiled without multibyte encoding support, pg_client_encoding() always returns SQL_ASCII." if (pg_set_client_encoding($this->_connection, 'UNICODE') == -1) { return false; } $this->_log['encoding'] = pg_client_encoding($this->_connection); return true; }
// If schema is defined and database supports schemas, then set the // schema explicitly. if (isset($_REQUEST['database']) && isset($_REQUEST['schema'])) { $status = $data->setSchema($_REQUEST['schema']); if ($status != 0) { echo $lang['strbadschema']; exit; } } // Get database encoding $dbEncoding = $data->getDatabaseEncoding(); // Set client encoding to database encoding if ($dbEncoding != '') { // Explicitly change client encoding if it's different to server encoding. if (function_exists('pg_client_encoding')) { $currEncoding = pg_client_encoding($data->conn->_connectionID); } elseif (function_exists('pg_clientencoding')) { $currEncoding = pg_clientencoding($data->conn->_connectionID); } else { $currEncoding = null; } if ($currEncoding != $dbEncoding) { $status = $data->setClientEncoding($dbEncoding); if ($status != 0 && $status != -99) { echo $lang['strbadencoding']; exit; } } // Override $lang['appcharset'] if (isset($data->codemap[$dbEncoding])) { $lang['appcharset'] = $data->codemap[$dbEncoding];
<?php // optional functions include 'config.inc'; $db = pg_connect($conn_str); $enc = pg_client_encoding($db); pg_set_client_encoding($db, $enc); if (function_exists('pg_set_error_verbosity')) { pg_set_error_verbosity(PGSQL_ERRORS_TERSE); pg_set_error_verbosity(PGSQL_ERRORS_DEFAULT); pg_set_error_verbosity(PGSQL_ERRORS_VERBOSE); } echo "OK";
public function ClientEncoding($enc) { return is_null($enc) ? pg_client_encoding($this->connection) : pg_set_client_encoding($this->connection, $enc); }
public function get_client_encoding() { return pg_client_encoding($this->handler); }
/** * Renvoie le jeu de caractères courant utilisé. * Si l'argument $encoding est fourni, il est utilisé pour définir * le nouveau jeu de caractères de la connexion en cours * * @param string $encoding * * @access public * @return string */ function encoding($encoding = null) { $curEncoding = pg_client_encoding($this->link); if (!is_null($encoding)) { pg_set_client_encoding($this->link, $encoding); } return $curEncoding; }
/** * getClientEncoding * * Return the actual client encoding. * * @access public * @return string */ public function getClientEncoding() { $encoding = pg_client_encoding($this->getHandler()); $this->testQuery($encoding, 'get client encoding'); return $encoding; }
if ($i == 2) { $dbuserpass = substr($buffer, 3, -1); } if ($i == 3) { $dbhost = substr($buffer, 3, -1); } if ($i == 4) { $dbport = substr($buffer, 3, -1); } //if($i==5) $dbtipo = substr($buffer,3,-1); $i++; } //if($dbtipo=='POSTGRESQL' || $dbtipo==''){ if ($dbhost == "") { $conn = "port={$dbport} user={$dbuser} password={$dbuserpass} dbname={$dbname}"; $connDebug = "port={$dbport} user={$dbuser} password=xxxxxx dbname={$dbname}"; } else { $conn = "host={$dbhost} port={$dbport} dbname={$dbname} user={$dbuser} password={$dbuserpass} "; $connDebug = "host={$dbhost} port={$dbport} dbname={$dbname} user={$dbuser} password=xxxxxx "; } $conexion = pg_connect($conn) or sysError("conectaBD.ejecutaConsulta.pg_connect->{$connDebug}"); $v = pg_version($conexion); $encoding = pg_client_encoding($conexion); pg_set_client_encoding($conexion, "UTF8"); /*} elseif($dbtipo=='MYSQL'){ $conexion = mysql_connect($dbhost, $dbuser, $dbuserpass); }*/ echo "Version: " . "<br/>"; print_r($v); echo "Encoding: " . $encoding . "<br/>";
/** * {@inheritdoc} */ public function getCharset() { return pg_client_encoding($this->connection); }
function IMPORTUSERS($hostname, $username, $pass) { global $SAMSConf; if ($SAMSConf->access != 2) { exit; } $this->DB = new SAMSDB($SAMSConf->DB_ENGINE, $SAMSConf->ODBC, $SAMSConf->DB_SERVER, $SAMSConf->DB_USER, $SAMSConf->DB_PASSWORD, $SAMSConf->SAMSDB, $SAMSConf->PDO); $this->oldDB = new SAMSDB("MySQL", "0", $hostname, $username, $pass, "squidctrl", "0"); echo "<BR>new: {$SAMSConf->DB_ENGINE}, {$SAMSConf->ODBC}, {$SAMSConf->DB_SERVER}, {$SAMSConf->DB_USER}, {$SAMSConf->DB_PASSWORD}, {$SAMSConf->SAMSDB}, {$SAMSConf->PDO}<BR>"; echo "old: MySQL, 0, {$hostname}, {$username}, {$pass}, squidctrl, 0<BR>"; $this->oldDB->samsdb_query_value("SELECT lang FROM globalsettings"); $row = $this->oldDB->samsdb_fetch_array(); $this->sams1charset = $row[0]; $this->oldDB->free_samsdb_query(); echo "charsert = {$this->sams1charset}<BR>"; $this->pgcharset = pg_client_encoding($this->DB->link); if ($SAMSConf->DB_ENGINE == "PostgreSQL" && $this->sams1charset != $this->pgcharset) { if ($this->sams1charset == "KOI8-R") { echo "<h3>ENCODING = {$this->sams1charset}</h3>"; pg_set_client_encoding("KOI8"); } } }
/** * Gets the database encoding * * @return string The database encoding */ function getEncoding() { return pg_client_encoding($this->connection); }
function cs_sql_version($cs_file) { global $cs_db; $sql_infos = array('data_free' => 0, 'data_size' => 0, 'index_size' => 0, 'tables' => 0, 'names' => array()); $sql_infos['type'] = 'PostgreSQL (pgsql)'; $sql_infos['host'] = pg_host($cs_db['con']) or cs_error_sql($cs_file, 'cs_sql_version', cs_sql_error()); if (function_exists('pg_version')) { $pg_infos = pg_version($cs_db['con']) or cs_error_sql($cs_file, 'cs_sql_version', cs_sql_error()); } $sql_infos['encoding'] = pg_client_encoding($cs_db['con']); $sql_infos['client'] = isset($pg_infos['client']) ? $pg_infos['client'] : '-'; $sql_infos['server'] = isset($pg_infos['server_version']) ? $pg_infos['server_version'] : '-'; if ($sql_infos['server'] == '-') { $found = cs_sql_query($cs_file, 'SELECT VERSION()', 1); preg_match('=[\\d|.]+=', $found['more'][0]['version'], $matches, PREG_OFFSET_CAPTURE); $sql_infos['server'] = isset($matches[0][0]) ? $matches[0][0] : $found['more'][0]['version']; } return $sql_infos; }
function GetCharSet() { //we will use ADO's builtin property charSet $this->charSet = @pg_client_encoding($this->_connectionID); if (!$this->charSet) { return false; } else { return $this->charSet; } }
/** * Create a PostgreSQL Server Custom Connection. * This MUST NOT be used with the default connection ... as that is handled automatically. * * @param STRING $yhost :: db host * @param STRING $yport :: db port * @param STRING $ydb :: db name * @param STRING $yuser :: db user * @param STRING $ypass :: db pass * @param INTEGER $ytimeout :: connection timeout * @param ENUM $y_transact_mode :: transactional mode ('READ COMMITTED' | 'REPEATABLE READ' | 'SERIALIZABLE' | '' to leave it as default) * @param FLOAT $y_debug_sql_slowtime :: debug query slow time * @param ENUM $y_type :: server type: postgresql or pgpool2 * * @return RESOURCE :: the postgresql connection resource ID * * @access private * @internal * */ public static function server_connect($yhost, $yport, $ydb, $yuser, $ypass, $ytimeout, $y_transact_mode = '', $y_debug_sql_slowtime = 0, $y_type = 'postgresql') { //-- if (defined('SMART_FRAMEWORK_DBSQL_CHARSET')) { if ((string) SMART_FRAMEWORK_DBSQL_CHARSET != 'UTF8') { die('The SMART_FRAMEWORK_DBSQL_CHARSET must be set as: UTF8'); } //end if } else { die('The SMART_FRAMEWORK_DBSQL_CHARSET must be set ...'); } //end if else //-- //-- if (!function_exists('pg_connect')) { self::error('[PRE-CONNECT]', 'PHP-PgSQL', 'Check PgSQL PHP Extension', 'PHP Extension is required to run this software !', 'Cannot find PgSQL PHP Extension'); return; } //end if //-- if ((string) ini_get('pgsql.ignore_notice') != '0') { // {{{SYNC-PGSQL-NOTIF-CHECK}}} self::error('[PRE-CONNECT]', 'PHP-Inits-PgSQL', 'Check PgSQL PHP.INI Settings', 'SETTINGS: PostgreSQL Notifications need to be ENABLED in PHP.INI !', 'SET in PHP.INI this: pgsql.ignore_notice = 0'); return; } //end if //-- //-- connection timeout $timeout = (int) $ytimeout; //-- if ($timeout < 1) { $timeout = 1; } //end if if ($timeout > 60) { $timeout = 60; } //end if //-- //-- debug settings if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') { //-- $y_debug_sql_slowtime = (double) $y_debug_sql_slowtime; if ($y_debug_sql_slowtime <= 0) { $y_debug_sql_slowtime = (double) self::$slow_time; } //end if //-- if ($y_debug_sql_slowtime < 1.0E-7) { $y_debug_sql_slowtime = 1.0E-7; } elseif ($y_debug_sql_slowtime > 0.9999999000000001) { $y_debug_sql_slowtime = 0.9999999000000001; } //end if //-- self::$slow_time = (double) $y_debug_sql_slowtime; // update //-- } //end if //-- //-- debug inits if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') { SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|slow-time', number_format(self::$slow_time, 7, '.', ''), '='); SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|log', ['type' => 'metainfo', 'data' => 'Database Server: PgSQL (' . $y_type . ') / App Connector Version: ' . SMART_FRAMEWORK_VERSION . ' / Connection Charset: ' . SMART_FRAMEWORK_DBSQL_CHARSET]); SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|log', ['type' => 'metainfo', 'data' => 'Connection Timeout: ' . $timeout . ' seconds / Fast Query Reference Time < ' . self::$slow_time . ' seconds']); } //end if //-- //-- if ((string) $ypass != '') { $password = (string) base64_decode((string) $ypass); } else { $password = ''; } //end if else //-- //-- {{{SYNC-CONNECTIONS-IDS}}} $the_conn_key = (string) $yhost . ':' . $yport . '@' . $ydb . '#' . $yuser . '>' . trim(strtoupper(str_replace(' ', '', (string) $y_transact_mode))) . '.'; //-- $connection = @pg_connect('host=' . $yhost . ' port=' . $yport . ' dbname=' . $ydb . ' user='******' password='******' connect_timeout=' . $timeout); // @pg_close($connection) (if is resource) ; but reusing connections policy dissalow disconnects //-- if (!is_resource($connection)) { self::error($yhost . ':' . $yport . '@' . $ydb . '#' . $yuser, 'Connection', 'Connect to PgSQL Server', 'NO CONNECTION !!!', 'Connection Failed to PgSQL Server !'); return; } //end if //-- if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') { SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|log', ['type' => 'open-close', 'data' => 'Connected to PgSQL Server: ' . $the_conn_key, 'connection' => (string) $connection]); } //end if //-- //-- @pg_set_error_verbosity($connection, PGSQL_ERRORS_DEFAULT); // this must be reset to PGSQL_ERRORS_DEFAULT and must NOT use PGSQL_ERRORS_VERBOSE because will affect write-igdata notice messages //-- $tmp_pg_tracefile = 'tmp/logs/pgsql-trace.log'; //-- if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') { //-- if (defined('SMART_FRAMEWORK_DEBUG_SQL_TRACE')) { if (function_exists('pg_trace')) { @pg_trace($tmp_pg_tracefile, 'w', $connection); // pg_trace can cause some PHP versions to crash (Ex: Debian 6.0.6 with PHP 5.3 / Apache 2.0.x) } //end if } //end if //-- } //end if else //-- //-- $result = @pg_query_params($connection, 'SELECT pg_encoding_to_char("encoding") FROM "pg_database" WHERE "datname" = $1', array($ydb)); if (!$result) { self::error($connection, 'Encoding-Charset', 'Check Query Failed', 'Error=' . @pg_last_error($connection), 'DB=' . $ydb); return; } //end if $server_encoding = @pg_fetch_row($result); if (trim($server_encoding[0]) != trim(SMART_FRAMEWORK_DBSQL_CHARSET)) { self::error($connection, 'Encoding-Get-Charset', 'Wrong Server Encoding on PgSQL Server', 'Server=' . $server_encoding[0], 'Client=' . SMART_FRAMEWORK_DBSQL_CHARSET); return; } //end if @pg_free_result($result); //-- //-- $encoding = @pg_set_client_encoding($connection, SMART_FRAMEWORK_DBSQL_CHARSET); //-- if ($encoding < 0 or (string) @pg_client_encoding() != (string) SMART_FRAMEWORK_DBSQL_CHARSET) { self::error($connection, 'Encoding-Check-Charset', 'Failed to set Client Encoding on PgSQL Server', 'Server=' . SMART_FRAMEWORK_DBSQL_CHARSET, 'Client=' . @pg_client_encoding()); return; } //end if //-- if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') { SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|log', ['type' => 'set', 'data' => 'SET Client Encoding [+check] to: ' . @pg_client_encoding(), 'connection' => (string) $connection, 'skip-count' => 'yes']); } //end if //-- //-- $transact = strtoupper((string) $y_transact_mode); switch ((string) $transact) { case 'SERIALIZABLE': case 'REPEATABLE READ': case 'READ COMMITTED': //-- $result = @pg_query($connection, 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ' . $transact); if (!$result) { self::error($connection, 'Set-Session-Transaction-Level', 'Failed to Set Session Transaction Level as ' . $transact, 'Error=' . @pg_last_error($connection), 'DB=' . $ydb); return; } //end if @pg_free_result($result); //-- $result = @pg_query('SHOW transaction_isolation'); $chk = @pg_fetch_row($result); if ((string) trim($chk[0]) == '' or (string) $transact != (string) strtoupper(trim($chk[0]))) { self::error($connection, 'Check-Session-Transaction-Level', 'Failed to Set Session Transaction Level as ' . $transact, 'Error=' . @pg_last_error($connection), 'DB=' . $ydb); return; } //end if if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') { SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|log', ['type' => 'set', 'data' => 'SET Session Transaction Isolation Level [+check] to: ' . strtoupper($chk[0]), 'connection' => (string) $connection, 'skip-count' => 'yes']); } //end if @pg_free_result($result); //-- break; default: // LEAVE THE SESSION TRANSACTION AS SET IN CFG } //end switch //-- //-- export only at the end (after all settings) SmartFrameworkRegistry::$Connections['pgsql'][(string) $the_conn_key] = $connection; // export connection //-- //-- OUTPUT return $connection; //-- OUTPUT }