Ejemplo n.º 1
0
function safe_dml_query($query, $verbose = True)
{
    global $conn;
    if ($verbose) {
        echo "------------------------\n";
        echo "Executing PG query: {$query}\n";
    }
    $time_start = microtime(true);
    pg_send_query($conn, $query) or die("Failed to execute query {$query}");
    while (pg_connection_busy($conn)) {
        if (microtime(true) - $time_start > 30) {
            if (rand(0, 10) == 0) {
                echo "Busy for " . round((microtime(true) - $time_start) * 1000) . " ms -";
            }
            sleep(5);
        }
        usleep(2000);
    }
    $res = pg_get_result($conn);
    if (pg_result_error($res) != null) {
        die("Error during query: " . pg_result_error($res) . "\n");
    }
    $time_end = microtime(true);
    $rows = pg_affected_rows($res);
    if ($verbose) {
        echo "Done executing {$query}: {$rows} touched\n";
        $t = round(($time_end - $time_start) * 1000);
        echo "Query time: {$t} ms\n";
        echo "------------------------\n";
    }
}
Ejemplo n.º 2
0
 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;
 }
Ejemplo n.º 3
0
function SQLLoad($file)
{
    header("SQL: {$file}", false);
    $con = db::RawConnection();
    $sql = file_get_contents($file);
    pg_send_query($con, $sql);
    if (($error = pg_last_error($con)) !== '') {
        die("Failure at loading {{$file}} with {{$error}}");
    }
    while (pg_connection_busy($con)) {
        sleep(1);
    }
    while (pg_get_result($con) !== false) {
        if (($error = pg_last_error($con)) !== '') {
            die("Failure at loading {{$file}} with {{$error}}");
        }
    }
}
Ejemplo n.º 4
0
 /**
  * Connection constructor.
  *
  * @param resource $handle PostgreSQL connection handle.
  * @param resource $socket PostgreSQL connection stream socket.
  */
 public function __construct($handle, $socket)
 {
     $this->handle = $handle;
     $this->poll = Loop\poll($socket, static function ($resource, bool $expired, Io $poll) use($handle) {
         /** @var \Icicle\Awaitable\Delayed $delayed */
         $delayed = $poll->getData();
         if (!\pg_consume_input($handle)) {
             $delayed->reject(new FailureException(\pg_last_error($handle)));
             return;
         }
         if (!\pg_connection_busy($handle)) {
             $delayed->resolve(\pg_get_result($handle));
             return;
         }
         $poll->listen();
         // Reading not done, listen again.
     });
     $this->await = Loop\await($socket, static function ($resource, bool $expired, Io $await) use($handle) {
         $flush = \pg_flush($handle);
         if (0 === $flush) {
             $await->listen();
             // Not finished sending data, listen again.
             return;
         }
         if (false === $flush) {
             /** @var \Icicle\Awaitable\Delayed $delayed */
             $delayed = $await->getData();
             $delayed->reject(new FailureException(\pg_last_error($handle)));
         }
     });
     $this->onCancelled = static function () use($handle) {
         \pg_cancel_query($handle);
     };
     $this->executeCallback = function (string $name, array $params) : \Generator {
         return $this->createResult(yield from $this->send('pg_send_execute', $name, $params));
     };
 }
Ejemplo n.º 5
0
 /**
  * Complete query
  * @param string $query query string
  * @param array|null $data query parameters
  * @return QueryResult postgres query result
  * @throws DuplicateEntryException when entry was duplicated
  * @throws DuplicateTableException when table was duplicated
  * @throws ConnectionBusyException when connection busy by another request
  * @throws UndefinedTableException when try to query undefined table
  * @throws QueryException for other reasons
  */
 public function query($query, array $data = null)
 {
     if (is_null($this->Resource)) {
         $this->connect();
     }
     $busy = false;
     if ($this->needBusyCheckup()) {
         $busy = pg_connection_busy($this->Resource);
     }
     if (!$busy) {
         $this->sendQuery($query, $data);
         $Result = pg_get_result($this->Resource);
         $Error = pg_result_error($Result);
         if (!empty($Error)) {
             $errorMessage = pg_errormessage($this->Resource);
             $errorCode = pg_result_error_field($Result, PGSQL_DIAG_SQLSTATE);
             switch ($errorCode) {
                 case self::CODE_DUPLICATE_ENTRY:
                     throw new DuplicateEntryException($errorMessage);
                 case self::CODE_UNDEFINED_TABLE:
                     throw new UndefinedTableException($errorMessage);
                 case self::CODE_DUPLICATE_TABLE:
                     throw new DuplicateTableException($errorMessage);
                 case self::CODE_DUPLICATE_TYPE:
                     throw new DuplicateTypeException($errorMessage);
                 case self::CODE_RAISE_EXCEPTION:
                     throw new RaiseException($errorMessage);
                 default:
                     throw new QueryException(sprintf("%s QUERY: %s CODE: %s", $errorMessage, $query, $errorCode));
             }
         } else {
             return new QueryResult($Result);
         }
     } else {
         throw new ConnectionBusyException();
     }
 }
Ejemplo n.º 6
0
                    }
                    $iLines++;
                    if ($iLines == 1000) {
                        echo ".";
                        $iLines = 0;
                    }
                }
            }
            usleep(10);
        }
        fclose($hFile);
        $bAnyBusy = true;
        while ($bAnyBusy) {
            $bAnyBusy = false;
            for ($i = 0; $i < $iInstances; $i++) {
                if (pg_connection_busy($aDBInstances[$i]->connection)) {
                    $bAnyBusy = true;
                }
            }
            usleep(10);
        }
        echo "\n";
    }
}
if ($aCMDResult['calculate-postcodes'] || $aCMDResult['all']) {
    $bDidSomething = true;
    $oDB =& getDB();
    if (!pg_query($oDB->connection, 'DELETE from placex where osm_type=\'P\'')) {
        fail(pg_last_error($oDB->connection));
    }
    $sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,country_code,geometry) ";
Ejemplo n.º 7
0
 public function IsBusy()
 {
     return pg_connection_busy($this->connection);
 }
Ejemplo n.º 8
0
<?php

$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
    pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}
$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): {$res1}\n";
$rows1 = pg_num_rows($res1);
echo "{$res1} has {$rows1} records\n\n";
$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): {$res2}\n";
$rows2 = pg_num_rows($res2);
echo "{$res2} has {$rows2} records\n";
Ejemplo n.º 9
0
 /**
  * Query the database.
  *
  * @param string $string The query SQL.
  * @param boolean|int $hide_errors 1 if hide errors, 0 if not.
  * @param integer $write_query 1 if executes on slave database, 0 if not.
  * @return resource The query data.
  */
 function query($string, $hide_errors = 0, $write_query = 0)
 {
     global $mybb;
     $string = preg_replace("#LIMIT (\\s*)([0-9]+),(\\s*)([0-9]+)\$#im", "LIMIT \$4 OFFSET \$2", trim($string));
     $this->last_query = $string;
     get_execution_time();
     if (strtolower(substr(ltrim($string), 0, 5)) == 'alter') {
         $string = preg_replace("#\\sAFTER\\s([a-z_]+?)(;*?)\$#i", "", $string);
         if (strstr($string, 'CHANGE') !== false) {
             $string = str_replace(' CHANGE ', ' ALTER ', $string);
         }
     }
     if ($write_query && $this->write_link) {
         while (pg_connection_busy($this->write_link)) {
         }
         $this->current_link =& $this->write_link;
         pg_send_query($this->current_link, $string);
         $query = pg_get_result($this->current_link);
     } else {
         while (pg_connection_busy($this->read_link)) {
         }
         $this->current_link =& $this->read_link;
         pg_send_query($this->current_link, $string);
         $query = pg_get_result($this->current_link);
     }
     if (pg_result_error($query) && !$hide_errors) {
         $this->error($string, $query);
         exit;
     }
     $query_time = get_execution_time();
     $this->query_time += $query_time;
     $this->query_count++;
     $this->last_result = $query;
     if ($mybb->debug_mode) {
         $this->explain_query($string, $query_time);
     }
     return $query;
 }
Ejemplo n.º 10
0
 /**
  * execute a prepared statement
  *
  * @param string $stmt_name
  * @param array $values
  * @uses self::error_string()
  * @return bool true / false
  */
 public function execute($stmt_name, array $values)
 {
     try {
         if (!@pg_connection_busy($this->dbh)) {
             $res = @pg_execute($this->dbh, $stmt_name, $values);
             if (!$res) {
                 throw new Exception('execute(): execute failed');
             }
         } else {
             throw new Exception('execute(): connection is busy ');
         }
     } catch (Exception $e) {
         self::error_string($e);
         return false;
     }
     return $res;
 }
Ejemplo n.º 11
0
 /**
  * Connects to the pgSQL database server
  *
  * This function connects to the PostgreSQL server and returns the connection object
  *
  * @return   object      Returns connection object
  *
  */
 function _connect()
 {
     if ($this->isVerbose()) {
         $this->_errorlog("\n*** Inside database->_connect ***");
     }
     // Connect to pgSQL server
     $this->_db = pg_connect($this->buildString()) or die('Cannot connect to DB server');
     if ($this->_pgsql_version == 0) {
         $v = pg_version($this->_db);
         $this->_pgsql_version = $v['client'];
     }
     if (!$this->_db) {
         if (pg_connection_busy($this->_db)) {
             if ($this->isVerbose()) {
                 $this->_errorlog("\n*** The current connection is busy ***");
             }
         } else {
             if ($this->isVerbose()) {
                 $this->_errorlog("\n*** Error in database->_connect ***");
             }
         }
     }
     if ($this->_pgsql_version >= 7.4 && $this->_charset == 'utf-8') {
         pg_query($this->_db, "SET NAMES 'UTF8'");
     }
     if ($this->isVerbose()) {
         $this->_errorlog("\n***leaving database->_connect***");
     }
 }
Ejemplo n.º 12
0
<?php

include 'config.inc';
$db = pg_connect($conn_str);
$version = pg_version($db);
if ($version['protocol'] >= 3) {
    if (!pg_send_query_params($db, "SELECT * FROM " . $table_name . " WHERE num > \$1;", array(100))) {
        echo "pg_send_query_params() error\n";
    }
    while (pg_connection_busy($db)) {
    }
    // busy wait: intended
    if (pg_connection_status($db) === PGSQL_CONNECTION_BAD) {
        echo "pg_connection_status() error\n";
    }
    if (!($result = pg_get_result($db))) {
        echo "pg_get_result() error\n";
    }
    if (!($rows = pg_num_rows($result))) {
        echo "pg_num_rows() error\n";
    }
    for ($i = 0; $i < $rows; $i++) {
        pg_fetch_array($result, $i, PGSQL_NUM);
    }
    for ($i = 0; $i < $rows; $i++) {
        pg_fetch_object($result);
    }
    for ($i = 0; $i < $rows; $i++) {
        pg_fetch_row($result, $i);
    }
    for ($i = 0; $i < $rows; $i++) {
Ejemplo n.º 13
0
<?php

// connection function tests
include 'config.inc';
$db = pg_pconnect($conn_str);
var_dump($db);
if (pg_connection_status($db) != PGSQL_CONNECTION_OK) {
    echo "pg_connection_status() error\n";
}
if (!pg_connection_reset($db)) {
    echo "pg_connection_reset() error\n";
}
if (pg_connection_busy($db)) {
    echo "pg_connection_busy() error\n";
}
if (function_exists('pg_transaction_status')) {
    if (pg_transaction_status($db) != PGSQL_TRANSACTION_IDLE) {
        echo "pg_transaction_status() error\n";
    }
}
if (false === pg_host($db)) {
    echo "pg_host() error\n";
}
if (!pg_dbname($db)) {
    echo "pg_dbname() error\n";
}
if (!pg_port($db)) {
    echo "pg_port() error\n";
}
if (pg_tty($db)) {
    echo "pg_tty() error\n";
Ejemplo n.º 14
0
 private function onReadable()
 {
     if (!\pg_consume_input($this->db)) {
         $this->onInputConsumptionFailure();
         return;
     }
     if (!\pg_connection_busy($this->db)) {
         $this->finalizeCompletedQueryResult();
     }
 }