function query($sql, $unbuffered = false) { if (strrpos($sql, 'LIMIT') !== false) { $sql = preg_replace('#LIMIT ([0-9]+),([ 0-9]+)#', 'LIMIT \\2 OFFSET \\1', $sql); } if (defined('PUN_SHOW_QUERIES')) { $q_start = get_microtime(); } @pg_send_query($this->link_id, $sql); $this->query_result = @pg_get_result($this->link_id); if (pg_result_status($this->query_result) != PGSQL_FATAL_ERROR) { if (defined('PUN_SHOW_QUERIES')) { $this->saved_queries[] = array($sql, sprintf('%.5f', get_microtime() - $q_start)); } ++$this->num_queries; $this->last_query_text[$this->query_result] = $sql; return $this->query_result; } else { if (defined('PUN_SHOW_QUERIES')) { $this->saved_queries[] = array($sql, 0); } $this->error_no = false; $this->error_msg = @pg_result_error($this->query_result); if ($this->in_transaction) { @pg_query($this->link_id, 'ROLLBACK'); } --$this->in_transaction; return false; } }
public static function castResult($result, array $a, Stub $stub, $isNested) { $a['num rows'] = pg_num_rows($result); $a['status'] = pg_result_status($result); if (isset(self::$resultStatus[$a['status']])) { $a['status'] = new ConstStub(self::$resultStatus[$a['status']], $a['status']); } $a['command-completion tag'] = pg_result_status($result, PGSQL_STATUS_STRING); if (-1 === $a['num rows']) { foreach (self::$diagCodes as $k => $v) { $a['error'][$k] = pg_result_error_field($result, $v); } } $a['affected rows'] = pg_affected_rows($result); $a['last OID'] = pg_last_oid($result); $fields = pg_num_fields($result); for ($i = 0; $i < $fields; ++$i) { $field = array('name' => pg_field_name($result, $i), 'table' => sprintf('%s (OID: %s)', pg_field_table($result, $i), pg_field_table($result, $i, true)), 'type' => sprintf('%s (OID: %s)', pg_field_type($result, $i), pg_field_type_oid($result, $i)), 'nullable' => (bool) pg_field_is_null($result, $i), 'storage' => pg_field_size($result, $i) . ' bytes', 'display' => pg_field_prtlen($result, $i) . ' chars'); if (' (OID: )' === $field['table']) { $field['table'] = null; } if ('-1 bytes' === $field['storage']) { $field['storage'] = 'variable size'; } elseif ('1 bytes' === $field['storage']) { $field['storage'] = '1 byte'; } if ('1 chars' === $field['display']) { $field['display'] = '1 char'; } $a['fields'][] = new EnumStub($field); } return $a; }
public function __construct($result, $sql, $as_object = FALSE, $params = NULL, $total_rows = NULL) { parent::__construct($result, $sql, $as_object, $params); if ($as_object === TRUE) { $this->_as_object = 'stdClass'; } if ($total_rows !== NULL) { $this->_total_rows = $total_rows; } else { switch (pg_result_status($result)) { case PGSQL_TUPLES_OK: $this->_total_rows = pg_num_rows($result); break; case PGSQL_COMMAND_OK: $this->_total_rows = pg_affected_rows($result); break; case PGSQL_BAD_RESPONSE: case PGSQL_NONFATAL_ERROR: case PGSQL_FATAL_ERROR: throw new Database_Exception(':error [ :query ]', array(':error' => pg_result_error($result), ':query' => $sql)); case PGSQL_COPY_OUT: case PGSQL_COPY_IN: throw new Database_Exception('PostgreSQL COPY operations not supported [ :query ]', array(':query' => $sql)); default: $this->_total_rows = 0; } } }
protected function &execute($query) { $result = pg_query($this->db, $query); if ($result === false) { throw new AleExceptionCache(pg_last_error($this->db), pg_result_status($result)); } return $result; }
function q($sql) { if (!$this->db || !$this->connected) { return false; } if (!strpos($sql, ';')) { $sql .= ';'; } if (strpos($sql, '`')) { // this is a hack. quoted identifiers should be replaced everywhere in the code with dbesc_identifier(), remove this once it is $sql = str_replace('`', '"', $sql); } $this->error = ''; $result = @pg_query($this->db, $sql); if (file_exists('db-allqueries.out')) { $bt = debug_backtrace(); $trace = array(); foreach ($bt as $frame) { if (!empty($frame['file']) && @strstr($frame['file'], $_SERVER['DOCUMENT_ROOT'])) { $frame['file'] = substr($frame['file'], strlen($_SERVER['DOCUMENT_ROOT']) + 1); } $trace[] = $frame['file'] . ':' . $frame['function'] . '():' . $frame['line']; } $compact = join(', ', $trace); file_put_contents('db-allqueries.out', datetime_convert() . ": " . $sql . ' is_resource: ' . var_export(is_resource($result), true) . ', backtrace: ' . $compact . "\n\n", FILE_APPEND); } if ($result === false) { $this->error = pg_last_error($this->db); } if ($result === false || $this->error) { //logger('dba_postgres: ' . printable($sql) . ' returned false.' . "\n" . $this->error); if (file_exists('dbfail.out')) { file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND); } } if ($result === true || $result === false) { return $result; } if (pg_result_status($result) == PGSQL_COMMAND_OK) { return true; } $r = array(); if (pg_num_rows($result)) { while ($x = pg_fetch_array($result, null, PGSQL_ASSOC)) { $r[] = $x; } pg_free_result($result); if ($this->debug) { logger('dba_postgres: ' . printable(print_r($r, true))); } } return $r; }
/** * @internal */ function checkError($res) { if ($res === false) { $in_error = true; $error = pg_last_error(); } else { if (pg_result_status($res) == PGSQL_FATAL_ERROR) { $in_error = true; $error = pg_result_error($res); } else { $error = ""; $in_error = false; } } }
/** * This is a callback function to display the result of each separate query * @param ADORecordSet $rs The recordset returned by the script execetor */ function sqlCallback($query, $rs, $lineno) { global $data, $misc, $lang, $_connection; // Check if $rs is false, if so then there was a fatal error if ($rs === false) { echo htmlspecialchars($_FILES['script']['name']), ':', $lineno, ': ', nl2br(htmlspecialchars($_connection->getLastError())), "<br/>\n"; } else { // Print query results switch (pg_result_status($rs)) { case PGSQL_TUPLES_OK: // If rows returned, then display the results $num_fields = pg_numfields($rs); echo "<p><table>\n<tr>"; for ($k = 0; $k < $num_fields; $k++) { echo "<th class=\"data\">", $misc->printVal(pg_fieldname($rs, $k)), "</th>"; } $i = 0; $row = pg_fetch_row($rs); while ($row !== false) { $id = $i % 2 == 0 ? '1' : '2'; echo "<tr class=\"data{$id}\">\n"; foreach ($row as $k => $v) { echo "<td style=\"white-space:nowrap;\">", $misc->printVal($v, pg_fieldtype($rs, $k), array('null' => true)), "</td>"; } echo "</tr>\n"; $row = pg_fetch_row($rs); $i++; } echo "</table><br/>\n"; echo $i, " {$lang['strrows']}</p>\n"; break; case PGSQL_COMMAND_OK: // If we have the command completion tag if (version_compare(phpversion(), '4.3', '>=')) { echo htmlspecialchars(pg_result_status($rs, PGSQL_STATUS_STRING)), "<br/>\n"; } elseif ($data->conn->Affected_Rows() > 0) { echo $data->conn->Affected_Rows(), " {$lang['strrowsaff']}<br/>\n"; } // Otherwise output nothing... break; case PGSQL_EMPTY_QUERY: break; default: break; } } }
function query($sql) { @pg_send_query($this->link_id, $sql); $this->query_result = @pg_get_result($this->link_id); if (pg_result_status($this->query_result) != PGSQL_FATAL_ERROR) { ++$this->num_queries; //$this->last_query_text[$this->query_result] = $sql; return $this->query_result; } else { if ($this->in_transaction) { @pg_query($this->link_id, "ROLLBACK"); } --$this->in_transaction; die(error(pg_result_error($this->query_result))); return false; } }
/** * Executes an SQL script as a series of SQL statements. Returns * the result of the final step. This is a very complicated lexer * based on the REL7_4_STABLE src/bin/psql/mainloop.c lexer in * the PostgreSQL source code. * XXX: It does not handle multibyte languages properly. * @param $name Entry in $_FILES to use * @param $callback (optional) Callback function to call with each query, its result and line number. * @return True for general success, false on any failure. */ function executeScript($name, $callback = null) { global $data; // This whole function isn't very encapsulated, but hey... $conn = $data->conn->_connectionID; if (!is_uploaded_file($_FILES[$name]['tmp_name'])) { return false; } $fd = fopen($_FILES[$name]['tmp_name'], 'r'); if (!$fd) { return false; } // Build up each SQL statement, they can be multiline $query_buf = null; $query_start = 0; $in_quote = 0; $in_xcomment = 0; $bslash_count = 0; $dol_quote = null; $paren_level = 0; $len = 0; $i = 0; $prevlen = 0; $thislen = 0; $lineno = 0; // Loop over each line in the file while (!feof($fd)) { $line = fgets($fd); $lineno++; // Nothing left on line? Then ignore... if (trim($line) == '') { continue; } $len = strlen($line); $query_start = 0; /* * Parse line, looking for command separators. * * The current character is at line[i], the prior character at line[i * - prevlen], the next character at line[i + thislen]. */ $prevlen = 0; $thislen = $len > 0 ? 1 : 0; for ($i = 0; $i < $len; $this->advance_1($i, $prevlen, $thislen)) { /* was the previous character a backslash? */ if ($i > 0 && substr($line, $i - $prevlen, 1) == '\\') { $bslash_count++; } else { $bslash_count = 0; } /* * It is important to place the in_* test routines before the * in_* detection routines. i.e. we have to test if we are in * a quote before testing for comments. */ /* in quote? */ if ($in_quote !== 0) { /* * end of quote if matching non-backslashed character. * backslashes don't count for double quotes, though. */ if (substr($line, $i, 1) == $in_quote && ($bslash_count % 2 == 0 || $in_quote == '"')) { $in_quote = 0; } } else { if ($dol_quote) { if (strncmp(substr($line, $i), $dol_quote, strlen($dol_quote)) == 0) { $this->advance_1($i, $prevlen, $thislen); while (substr($line, $i, 1) != '$') { $this->advance_1($i, $prevlen, $thislen); } $dol_quote = null; } } else { if (substr($line, $i, 2) == '/*') { $in_xcomment++; if ($in_xcomment == 1) { $this->advance_1($i, $prevlen, $thislen); } } else { if ($in_xcomment) { if (substr($line, $i, 2) == '*/' && !--$in_xcomment) { $this->advance_1($i, $prevlen, $thislen); } } else { if (substr($line, $i, 1) == '\'' || substr($line, $i, 1) == '"') { $in_quote = substr($line, $i, 1); } else { if (!$dol_quote && $this->valid_dolquote(substr($line, $i))) { $dol_end = strpos(substr($line, $i + 1), '$'); $dol_quote = substr($line, $i, $dol_end + 1); $this->advance_1($i, $prevlen, $thislen); while (substr($line, $i, 1) != '$') { $this->advance_1($i, $prevlen, $thislen); } } else { if (substr($line, $i, 2) == '--') { $line = substr($line, 0, $i); /* remove comment */ break; } else { if (substr($line, $i, 1) == '(') { $paren_level++; } else { if (substr($line, $i, 1) == ')' && $paren_level > 0) { $paren_level--; } else { if (substr($line, $i, 1) == ';' && !$bslash_count && !$paren_level) { $subline = substr(substr($line, 0, $i), $query_start); /* is there anything else on the line? */ if (strspn($subline, " \t\n\r") != strlen($subline)) { /* * insert a cosmetic newline, if this is not the first * line in the buffer */ if (strlen($query_buf) > 0) { $query_buf .= "\n"; } /* append the line to the query buffer */ $query_buf .= $subline; $query_buf .= ';'; // Execute the query. PHP cannot execute // empty queries, unlike libpq $res = @pg_query($conn, $query_buf); // Call the callback function for display if ($callback !== null) { $callback($query_buf, $res, $lineno); } // Check for COPY request if (pg_result_status($res) == 4) { // 4 == PGSQL_COPY_FROM while (!feof($fd)) { $copy = fgets($fd, 32768); $lineno++; pg_put_line($conn, $copy); if ($copy == "\\.\n" || $copy == "\\.\r\n") { pg_end_copy($conn); break; } } } } $query_buf = null; $query_start = $i + $thislen; } else { if (preg_match('/^[_[:alpha:]]$/', substr($line, $i, 1))) { $sub = substr($line, $i, $thislen); while (preg_match('/^[\\$_A-Za-z0-9]$/', $sub)) { /* keep going while we still have identifier chars */ $this->advance_1($i, $prevlen, $thislen); $sub = substr($line, $i, $thislen); } // Since we're now over the next character to be examined, it is necessary // to move back one space. $i -= $prevlen; } } } } } } } } } } } } // end for /* Put the rest of the line in the query buffer. */ $subline = substr($line, $query_start); if ($in_quote || $dol_quote || strspn($subline, " \t\n\r") != strlen($subline)) { if (strlen($query_buf) > 0) { $query_buf .= "\n"; } $query_buf .= $subline; } $line = null; } // end while /* * Process query at the end of file without a semicolon, so long as * it's non-empty. */ if (strlen($query_buf) > 0 && strspn($query_buf, " \t\n\r") != strlen($query_buf)) { // Execute the query $res = @pg_query($conn, $query_buf); // Call the callback function for display if ($callback !== null) { $callback($query_buf, $res, $lineno); } // Check for COPY request if (pg_result_status($res) == 4) { // 4 == PGSQL_COPY_FROM while (!feof($fd)) { $copy = fgets($fd, 32768); $lineno++; pg_put_line($conn, $copy); if ($copy == "\\.\n" || $copy == "\\.\r\n") { pg_end_copy($conn); break; } } } } fclose($fd); return true; }
/** * Executes a given query with the ability to pass parameters separately * * @param string $sql Query * @param array $params Parameters * @param array $inputTypes Parameter types * @param array $outputTypes Result types to pass to ResultSet * @return bool|ResultSet|int * @throws exceptions\InvalidQueryException */ public function executeParams($sql, array $params, array $inputTypes = array(), array $outputTypes = array()) { if (!$this->isConnected()) { $this->connect(); } $stringParams = array(); foreach ($params as $key => $value) { if (isset($inputTypes[$key])) { $stringParams[$key] = $this->getTypeConverter($inputTypes[$key])->output($value); } else { $stringParams[$key] = $this->guessOutputFormat($value); } } $result = @pg_query_params($this->getResource(), $sql, $stringParams); if (false === $result) { throw new exceptions\InvalidQueryException(pg_last_error($this->getResource())); } switch (pg_result_status($result)) { case PGSQL_COMMAND_OK: $rows = pg_affected_rows($result); pg_free_result($result); return $rows; case PGSQL_COPY_IN: case PGSQL_COPY_OUT: pg_free_result($result); return true; case PGSQL_TUPLES_OK: default: return new ResultSet($result, $this->getTypeConverterFactory(), $outputTypes); } }
function Close() { if (version_compare(phpversion(), "4.2.0", "ge") > 0) { if (!$this->oid) { echo "{$this->error}<br>\n"; } else { $this->result = pg_result_status($this->result); $this->error = pg_lo_close($this->oid); } } }
function wpsql_errno($connection) { // throw new Exception("Error Processing Request", 1); if ($connection == 1) { return false; } $result = pg_get_result($connection); $result_status = pg_result_status($result); return pg_result_error_field($result_status, PGSQL_DIAG_SQLSTATE); }
private function _pg_query($aArguments = array(), $aOKStatuses = array(PGSQL_TUPLES_OK)) { if (is_scalar($aArguments)) { $aArguments = array($aArguments); } $iLevel = error_reporting(); // to suppress E_WARNING that can happen error_reporting(0); $rQueryResult = pg_query($this->rConnection, $this->process($aArguments)); $this->iLastResult = pg_result_status($rQueryResult); error_reporting($iLevel); if (!$this->isResultOK($aOKStatuses)) { if ($aArguments == array('ROLLBACK;')) { // first false forces throwException to use pg_last_error // second false prevents recursion: // throwException -> say rollback -> unable to say rollback (e.g. server has gone) -> // --> throwException -> say rollback -> unable to say rollback --> ... $this->throwException(false, false); } else { $this->throwException(); } } $this->iAffectedRowsCount = (int) pg_affected_rows($rQueryResult); $this->iRows = (int) pg_num_rows($rQueryResult); return $rQueryResult; }
/** * getQueryResult * * Get an asynchronous query result. * The only reason for the SQL query to be passed as parameter is to throw * a meaningful exception when an error is raised. * Since it is possible to send several queries at a time, This method can * return an array of ResultHandler. * * @access protected * @param string (default null) * @throws ConnectionException if no response are available. * @throws SqlException if the result is an error. * @return ResultHandler|array */ protected function getQueryResult($sql = null) { $results = []; while ($result = pg_get_result($this->getHandler())) { $status = pg_result_status($result, \PGSQL_STATUS_LONG); if ($status !== \PGSQL_COMMAND_OK && $status !== \PGSQL_TUPLES_OK) { throw new SqlException($result, $sql); } $results[] = new ResultHandler($result); } if (count($results) === 0) { throw new ConnectionException(sprintf("There are no waiting results in connection.\nQuery = '%s'.", $sql)); } return count($results) === 1 ? $results[0] : $results; }
function hasResult($stack = 0) { return @pg_result_status($this->result[$stack]) == PGSQL_TUPLES_OK; }
protected function run_command($command) { $result = pg_query($this->conn, $command); if ($result === false) { return false; } return pg_result_status($result) === PGSQL_COMMAND_OK; }
/** * Execute any statement * * @param string sql * @param bool buffered default TRUE * @return rdbms.pgsql.PostgreSQLResultSet or TRUE if no resultset was created * @throws rdbms.SQLException */ protected function query0($sql, $buffered = TRUE) { if (!is_resource($this->handle)) { if (!($this->flags & DB_AUTOCONNECT)) { throw new SQLStateException('Not connected'); } $c = $this->connect(); // Check for subsequent connection errors if (FALSE === $c) { throw new SQLStateException('Previously failed to connect.'); } } $success = pg_send_query($this->handle, $sql); if (!$success) { $message = 'Statement failed: ' . rtrim(pg_last_error($this->handle)) . ' @ ' . $this->dsn->getHost(); if (PGSQL_CONNECTION_OK !== pg_connection_status($this->handle)) { throw new SQLConnectionClosedException($message, $sql); } else { throw new SQLStatementFailedException($message, $sql); } } $this->result = pg_get_result($this->handle); switch ($status = pg_result_status($this->result, PGSQL_STATUS_LONG)) { case PGSQL_FATAL_ERROR: case PGSQL_BAD_RESPONSE: $code = pg_result_error_field($this->result, PGSQL_DIAG_SQLSTATE); $message = 'Statement failed: ' . pg_result_error_field($this->result, PGSQL_DIAG_MESSAGE_PRIMARY) . ' @ ' . $this->dsn->getHost(); if ('40P01' === $code) { throw new SQLDeadlockException($message, $sql, $code); } else { throw new SQLStatementFailedException($message, $sql, $code); } case PGSQL_COMMAND_OK: return TRUE; default: return new PostgreSQLResultSet($this->result, $this->tz); } }
<?php include 'config.inc'; $db = pg_connect($conn_str); $sql = "SELECT * FROM " . $table_name . " WHERE num = -2"; $result = pg_query($db, "BEGIN;END"); echo pg_result_status($result) . "\n"; echo pg_result_status($result, PGSQL_STATUS_STRING) . "\n";
/** * Executes a prepared query * * @param array $params Input params for query. * @param array $resultTypes Types information, used to convert output values (overrides auto-generated types). * @return ResultSet|int|bool Execution result. * @throws exceptions\TypeConversionException * @throws exceptions\InvalidQueryException */ public function execute(array $params = array(), array $resultTypes = array()) { if (!empty($params)) { $this->_values = array(); foreach (array_values($params) as $i => $value) { $this->bindValue($i + 1, $value); } } $params = array(); foreach ($this->_values as $key => $value) { if (isset($this->_converters[$key])) { $params[$key] = $this->_converters[$key]->output($value); } else { $params[$key] = $this->_connection->guessOutputFormat($value); } } $result = @pg_execute($this->_connection->getResource(), $this->_queryId, $params); if (!$result) { throw new exceptions\InvalidQueryException(pg_last_error($this->_connection->getResource())); } switch (pg_result_status($result)) { case PGSQL_COPY_IN: case PGSQL_COPY_OUT: pg_free_result($result); return true; case PGSQL_COMMAND_OK: $count = pg_affected_rows($result); pg_free_result($result); return $count; case PGSQL_TUPLES_OK: default: return new ResultSet($result, $this->_connection->getTypeConverterFactory(), $resultTypes); } }
public function query($type, $sql, $as_object = FALSE, array $params = NULL) { $this->_connection or $this->connect(); if (Kohana::$profiling) { // Benchmark this query for the current instance $benchmark = Profiler::start("Database ({$this->_instance})", $sql); } try { if ($type === Database::INSERT and $this->_config['primary_key']) { $sql .= ' RETURNING ' . $this->quote_identifier($this->_config['primary_key']); } try { $result = pg_query($this->_connection, $sql); } catch (Exception $e) { throw new Database_Exception(':error [ :query ]', array(':error' => pg_last_error($this->_connection), ':query' => $sql)); } if (!$result) { throw new Database_Exception(':error [ :query ]', array(':error' => pg_last_error($this->_connection), ':query' => $sql)); } // Check the result for errors switch (pg_result_status($result)) { case PGSQL_COMMAND_OK: $rows = pg_affected_rows($result); break; case PGSQL_TUPLES_OK: $rows = pg_num_rows($result); break; case PGSQL_BAD_RESPONSE: case PGSQL_NONFATAL_ERROR: case PGSQL_FATAL_ERROR: throw new Database_Exception(':error [ :query ]', array(':error' => pg_result_error($result), ':query' => $sql)); case PGSQL_COPY_OUT: case PGSQL_COPY_IN: pg_end_copy($this->_connection); throw new Database_Exception('PostgreSQL COPY operations not supported [ :query ]', array(':query' => $sql)); default: $rows = 0; } if (isset($benchmark)) { Profiler::stop($benchmark); } $this->last_query = $sql; if ($type === Database::SELECT) { return new Database_PostgreSQL_Result($result, $sql, $as_object, $params, $rows); } if ($type === Database::INSERT) { if ($this->_config['primary_key']) { // Fetch the first column of the last row $insert_id = pg_fetch_result($result, $rows - 1, 0); } elseif ($insert_id = pg_send_query($this->_connection, 'SELECT LASTVAL()')) { if ($result = pg_get_result($this->_connection) and pg_result_status($result) === PGSQL_TUPLES_OK) { $insert_id = pg_fetch_result($result, 0); } } return array($insert_id, $rows); } return $rows; } catch (Exception $e) { if (isset($benchmark)) { Profiler::delete($benchmark); } throw $e; } }
public function insert_id() { if ($this->insert_id === NULL) { $this->insert_id = FALSE; if ($result = pg_send_query($this->link, 'SELECT LASTVAL()')) { $result = pg_get_result($this->link); if (is_resource($result)) { if (pg_result_status($result) === PGSQL_TUPLES_OK) { $this->insert_id = pg_fetch_result($result, 0); } pg_free_result($result); } } } return $this->insert_id; }
function hasResult($stack = 0) { return @pg_result_status($this->result[$stack]) == PGSQL_TUPLES_OK; //( is_resource($this->result[$stack]) && get_resource_type($this->result[$stack]) === 'pgsql result' ) }
function query($sql, $unbuffered = false) { if (strlen($sql) > FORUM_DATABASE_QUERY_MAXIMUM_LENGTH) { exit('Insane query. Aborting.'); } if (strrpos($sql, 'LIMIT') !== false) { $sql = preg_replace('#LIMIT ([0-9]+),([ 0-9]+)#', 'LIMIT \\2 OFFSET \\1', $sql); } if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG')) { $q_start = forum_microtime(); } @pg_send_query($this->link_id, $sql); $this->query_result = @pg_get_result($this->link_id); if (pg_result_status($this->query_result) != PGSQL_FATAL_ERROR) { if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG')) { $this->saved_queries[] = array($sql, sprintf('%.5f', forum_microtime() - $q_start)); } ++$this->num_queries; $this->last_query_text[$this->query_result] = $sql; return $this->query_result; } else { if (defined('FORUM_SHOW_QUERIES') || defined('FORUM_DEBUG')) { $this->saved_queries[] = array($sql, 0); } $this->error_msg = @pg_result_error($this->query_result); if ($this->in_transaction) { @pg_query($this->link_id, 'ROLLBACK'); } --$this->in_transaction; return false; } }
$query = "VACUUM ANALYZE pages"; $result = pg_query($pgconn, $query); if (pg_result_status($result) == PGSQL_COMMAND_OK) { echo "Vacuum OK\n"; } else { echo "ERREUR lors du Vacuum !\n" . pg_last_error($pgconn); } $query = "DROP TABLE mots CASCADE"; $result = pg_query($pgconn, $query); if (pg_result_status($result) == PGSQL_COMMAND_OK) { echo "Suppression de la table mots OK\n"; } else { echo "ERREUR lors de la suppression !\n" . pg_last_error($pgconn); } $query = "CREATE TABLE mots AS\n SELECT word AS mot FROM ts_stat('SELECT to_tsvector(''simple'', contenu) FROM pages')"; $result = pg_query($pgconn, $query); if (pg_result_status($result) == PGSQL_COMMAND_OK) { echo "Création de la table mots OK\n"; } else { echo "ERREUR lors de la création !\n" . pg_last_error($pgconn); } $query = "CREATE INDEX mots_idx ON mots USING gin(mot gin_trgm_ops)"; $result = pg_query($pgconn, $query); if (pg_result_status($result) == PGSQL_COMMAND_OK) { echo "Création de l'index pour la table mots OK\n"; } else { echo "ERREUR lors de la création !\n" . pg_last_error($pgconn); } closedir($handle); } pg_close($pgconn);
/** * @param resource $result PostgreSQL result resource. * * @return \Icicle\Postgres\CommandResult|\Icicle\Postgres\TupleResult * * @throws \Icicle\Postgres\Exception\FailureException * @throws \Icicle\Postgres\Exception\QueryError */ private function createResult($result) { switch (\pg_result_status($result, \PGSQL_STATUS_LONG)) { case \PGSQL_EMPTY_QUERY: throw new QueryError('Empty query string'); case \PGSQL_COMMAND_OK: return new CommandResult($result); case \PGSQL_TUPLES_OK: return new TupleResult($result); case \PGSQL_NONFATAL_ERROR: case \PGSQL_FATAL_ERROR: throw new QueryError(\pg_result_error($result)); case \PGSQL_BAD_RESPONSE: throw new FailureException(\pg_result_error($result)); default: throw new FailureException('Unknown result status'); } }
/** * errorInfo * * @method errorInfo * @return string */ public function errorInfo() { return pg_result_status($this->_con, PGSQL_STATUS_STRING); }
/** * @throws DBQueryException * @param ISqlQUery $query * @param boolean $isAsync * @return resource */ protected function performQuery(ISqlQuery $query, $isAsync) { Assert::isBoolean($isAsync); $parameters = $query->getPlaceholderValues($this->getDialect()); $queryAsString = $query->toDialectString($this->getDialect()); if ($isAsync) { LoggerPool::log(parent::LOG_VERBOSE, 'sending an async query: %s', $queryAsString); } else { LoggerPool::log(parent::LOG_VERBOSE, 'sending query: %s', $queryAsString); } LoggerPool::log(parent::LOG_QUERY, $queryAsString); $executeResult = pg_send_query($this->link, $queryAsString); if (!$isAsync || !$executeResult) { $result = pg_get_result($this->link); $resultStatus = pg_result_status($result, PGSQL_STATUS_LONG); if (in_array($resultStatus, array(PGSQL_EMPTY_QUERY, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR, PGSQL_FATAL_ERROR))) { $errorCode = pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); $errorMessage = pg_result_error_field($result, PGSQL_DIAG_MESSAGE_PRIMARY); if (PgSqlError::UNIQUE_VIOLATION == $errorCode) { LoggerPool::log(parent::LOG_VERBOSE, 'query caused a unique violation: %s', $errorMessage); throw new UniqueViolationException($query, $errorMessage); } else { LoggerPool::log(parent::LOG_VERBOSE, 'query caused an error #%s: %s', $errorCode, $errorMessage); throw new PgSqlQueryException($query, $errorMessage, $errorCode); } } } return $result; }
static function check_status(&$res) { $status = pg_result_status($res); switch ($status) { case PGSQL_EMPTY_QUERY: throw new kdb_query_err("Server got empty SQL query."); break; case PGSQL_COMMAND_OK: case PGSQL_TUPLES_OK: case PGSQL_COPY_OUT: case PGSQL_COPY_IN: break; case PGSQL_BAD_RESPONSE: throw new kdb_query_err("Bad response from DB server."); break; case PGSQL_NONFATAL_ERROR: case PGSQL_FATAL_ERROR: throw new kdb_query_err(pg_result_error($res)); break; } }
function wpsql_errno($connection) { $result = pg_get_result($connection); $result_status = pg_result_status($result); return pg_result_error_field($result_status, PGSQL_DIAG_SQLSTATE); }
pg_lo_seek($obj,0,PGSQL_SEEK_SET); $res = pg_lo_read($obj,$len) or pgerr( 'lo_read failed' ); pg_lo_close($obj); dump($res); } else { $result = pg_query($req) or pgerr("error at request: $req"); if( pg_result_status($result) == PGSQL_COMMAND_OK ) { dump( 0 ); dump( pg_affected_rows($result) ); dump( pg_last_oid($result) ); pg_free_result($result); } elseif( pg_result_status($result) == PGSQL_EMPTY_QUERY ) { dump( 0 ); dump( 0 ); pg_free_result($result); } elseif( pg_result_status($result) == PGSQL_TUPLES_OK ) { $width = pg_num_fields($result); $height = pg_num_rows($result); dump($width); dump($height); for( $i = 0; $i < $width; ++$i ) { $type = pg_field_type( $result, $i ); dump( pg_field_name( $result, $i ) ); dump( $type ); dump( pg_field_size( $result, $i ) ); } for( $i = 0; $i < $height; ++$i ) { $row = pg_fetch_row( $result ); for( $j = 0; $j < $width; ++$j ) if( is_null($row[$j]) ) dump( '' );