The PostgreSQL connection class. The interface for this class is based on libpq, the C application programmer’s interface to PostgreSQL. Some familiarity with libpq is recommended, but not necessary.
For example, to send query to the database on the localhost:
require 'pg' conn = PG::Connection.open(:dbname => 'test') res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil]) # Equivalent to: # res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
See the PG::Result
class for information on working with the results of a query.
Many methods of this class have three variants kind of:
exec
- the base method which is an alias to async_exec
. This is the method that should be used in general.
async_exec
- the async aware version of the method, implemented by libpq’s async API.
sync_exec
- the method version that is implemented by blocking function(s) of libpq.
Sync and async version of the method can be switched by Connection.async_api=
, however it is not recommended to change the default.
The order the options are passed to the ::connect
method.
These methods are affected by PQsetnonblocking
Switch between sync and async libpq API.
PG::Connection.async_api = true
this is the default. It sets an alias from exec
to async_exec
, reset
to async_reset
and so on.
PG::Connection.async_api = false
sets an alias from exec
to sync_exec
, reset
to sync_reset
and so on.
pg-1.1.0+ defaults to libpq’s async API for query related blocking methods. pg-1.3.0+ defaults to libpq’s async API for all possibly blocking methods.
PLEASE NOTE: This method is not part of the public API and is for debug and development use only. Do not use this method in production code. Any issues with the default setting of async_api=true
should be reported to the maintainers instead.
# File lib/pg/connection.rb, line 863
def async_api=(enable)
self.async_send_api = enable
REDIRECT_METHODS.each do |ali, (async, sync)|
remove_method(ali) if method_defined?(ali)
alias_method( ali, enable ? async : sync )
end
REDIRECT_CLASS_METHODS.each do |ali, (async, sync)|
singleton_class.remove_method(ali) if method_defined?(ali)
singleton_class.alias_method(ali, enable ? async : sync )
end
end
# File lib/pg/connection.rb, line 840
def async_send_api=(enable)
REDIRECT_SEND_METHODS.each do |ali, (async, sync)|
undef_method(ali) if method_defined?(ali)
alias_method( ali, enable ? async : sync )
end
end
Returns an array of hashes. Each hash has the keys:
:keyword
the name of the option
:envvar
the environment variable to fall back to
:compiled
the compiled in option as a secondary fallback
:val
the option’s current value, or nil
if not known
:label
the label for the field
:dispchar
“” for normal, “D” for debug, and “*” for password
:dispsize
field size
static VALUE
pgconn_s_conndefaults(VALUE self)
{
PQconninfoOption *options = PQconndefaults();
VALUE array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
UNUSED( self );
return array;
}
Return the Postgres connection defaults structure as a Hash keyed by option keyword (as a Symbol).
See also conndefaults
# File lib/pg/connection.rb, line 260
def self.conndefaults_hash
return self.conndefaults.each_with_object({}) do |info, hash|
hash[ info[:keyword].to_sym ] = info[:val]
end
end
Convert Hash options to connection String
Values are properly quoted and escaped.
# File lib/pg/connection.rb, line 44
def self.connect_hash_to_string( hash )
hash.map { |k,v| "#{k}=#{quote_connstr(v)}" }.join( ' ' )
end
This is an asynchronous version of PG::Connection.new
.
Use connect_poll
to poll the status of the connection.
NOTE: this does not set the connection’s client_encoding
for you if Encoding.default_internal
is set. To set it after the connection is established, call internal_encoding=
. You can also set it automatically by setting ENV['PGCLIENTENCODING']
, or include the ‘options’ connection parameter.
See also the ‘sample’ directory of this gem and the corresponding libpq functions.
static VALUE
pgconn_s_connect_start( int argc, VALUE *argv, VALUE klass )
{
VALUE rb_conn;
VALUE conninfo;
t_pg_connection *this;
/*
* PG::Connection.connect_start must act as both alloc() and initialize()
* because it is not invoked by calling new().
*/
rb_conn = pgconn_s_allocate( klass );
this = pg_get_connection( rb_conn );
conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
this->pgconn = gvl_PQconnectStart( StringValueCStr(conninfo) );
if( this->pgconn == NULL )
rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate PGconn structure");
if ( PQstatus(this->pgconn) == CONNECTION_BAD )
pg_raise_conn_error( rb_eConnectionBad, rb_conn, "%s", PQerrorMessage(this->pgconn));
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn );
}
return rb_conn;
}
Returns parsed connection options from the provided connection string as an array of hashes. Each hash has the same keys as PG::Connection.conndefaults()
. The values from the conninfo_string
are stored in the :val
key.
static VALUE
pgconn_s_conninfo_parse(VALUE self, VALUE conninfo)
{
VALUE array;
char *errmsg = NULL;
PQconninfoOption *options = PQconninfoParse(StringValueCStr(conninfo), &errmsg);
if(errmsg){
VALUE error = rb_str_new_cstr(errmsg);
PQfreemem(errmsg);
rb_raise(rb_ePGerror, "%"PRIsVALUE, error);
}
array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
UNUSED( self );
return array;
}
This is an older, deprecated version of encrypt_password
. The difference is that this function always uses md5
as the encryption algorithm.
static VALUE
pgconn_s_encrypt_password(VALUE self, VALUE password, VALUE username)
{
char *encrypted = NULL;
VALUE rval = Qnil;
UNUSED( self );
Check_Type(password, T_STRING);
Check_Type(username, T_STRING);
encrypted = PQencryptPassword(StringValueCStr(password), StringValueCStr(username));
rval = rb_str_new2( encrypted );
PQfreemem( encrypted );
return rval;
}
Escapes binary data for use within an SQL command with the type bytea
.
Certain byte values must be escaped (but all byte values may be escaped) when used as part of a bytea
literal in an SQL statement. In general, to escape a byte, it is converted into the three digit octal number equal to the octet value, and preceded by two backslashes. The single quote (‘) and backslash () characters have special alternative escape sequences. escape_bytea
performs this operation, escaping only the minimally required bytes.
Consider using exec_params
, which avoids the need for passing values inside of SQL commands.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
static VALUE
pgconn_s_escape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t from_len, to_len;
VALUE ret;
Check_Type(str, T_STRING);
from = (unsigned char*)RSTRING_PTR(str);
from_len = RSTRING_LEN(str);
if ( rb_obj_is_kind_of(self, rb_cPGconn) ) {
to = PQescapeByteaConn(pg_get_pgconn(self), from, from_len, &to_len);
} else {
to = PQescapeBytea( from, from_len, &to_len);
}
ret = rb_str_new((char*)to, to_len - 1);
PQfreemem(to);
return ret;
}
Returns a SQL-safe version of the String str. This is the preferred way to make strings safe for inclusion in SQL queries.
Consider using exec_params
, which avoids the need for passing values inside of SQL commands.
Character encoding of escaped string will be equal to client encoding of connection.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
See also convenience functions escape_literal
and escape_identifier
which also add proper quotes around the string.
static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
size_t size;
int error;
VALUE result;
int enc_idx;
int singleton = !rb_obj_is_kind_of(self, rb_cPGconn);
StringValueCStr(string);
enc_idx = singleton ? ENCODING_GET(string) : pg_get_connection(self)->enc_idx;
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
result = rb_str_new(NULL, RSTRING_LEN(string) * 2 + 1);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
if( !singleton ) {
size = PQescapeStringConn(pg_get_pgconn(self), RSTRING_PTR(result),
RSTRING_PTR(string), RSTRING_LEN(string), &error);
if(error)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(pg_get_pgconn(self)));
} else {
size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
}
rb_str_set_len(result, size);
return result;
}
Create a connection to the specified server.
connection_hash
must be a ruby Hash with connection parameters. See the list of valid parameters in the PostgreSQL documentation.
There are two accepted formats for connection_string
: plain keyword = value
strings and URIs. See the documentation of connection strings.
The positional parameter form has the same functionality except that the missing parameters will always take on default values. The parameters are:
host
server hostname
port
server port number
options
backend options
tty
(ignored in all versions of PostgreSQL)
dbname
connecting database name
user
login user name
password
login password
Examples:
# Connect using all defaults PG::Connection.new # As a Hash PG::Connection.new( dbname: 'test', port: 5432 ) # As a String PG::Connection.new( "dbname=test port=5432" ) # As an Array PG::Connection.new( nil, 5432, nil, nil, 'test', nil, nil ) # As an URI PG::Connection.new( "postgresql://user:pass@pgsql.example.com:5432/testdb?sslmode=require" )
If the Ruby default internal encoding is set (i.e., Encoding.default_internal != nil
), the connection will have its client_encoding
set accordingly.
Raises a PG::Error
if the connection fails.
# File lib/pg/connection.rb, line 659
def new(*args, **kwargs)
conn = connect_to_hosts(*args, **kwargs)
if block_given?
begin
return yield conn
ensure
conn.finish
end
end
conn
end
Parse the connection args
into a connection-parameter string. See PG::Connection.new
for valid arguments.
It accepts:
an option String kind of “host=name port=5432”
an option Hash kind of {host: “name”, port: 5432}
URI string
URI object
positional arguments
The method adds the option “fallback_application_name” if it isn’t already set. It returns a connection string with “key=value” pairs.
# File lib/pg/connection.rb, line 60
def self.parse_connect_args( *args )
hash_arg = args.last.is_a?( Hash ) ? args.pop.transform_keys(&:to_sym) : {}
iopts = {}
if args.length == 1
case args.first
when URI, /=/, /:\/\//
# Option or URL string style
conn_string = args.first.to_s
iopts = PG::Connection.conninfo_parse(conn_string).each_with_object({}){|h, o| o[h[:keyword].to_sym] = h[:val] if h[:val] }
else
# Positional parameters (only host given)
iopts[CONNECT_ARGUMENT_ORDER.first.to_sym] = args.first
end
else
# Positional parameters with host and more
max = CONNECT_ARGUMENT_ORDER.length
raise ArgumentError,
"Extra positional parameter %d: %p" % [ max + 1, args[max] ] if args.length > max
CONNECT_ARGUMENT_ORDER.zip( args ) do |(k,v)|
iopts[ k.to_sym ] = v if v
end
iopts.delete(:tty) # ignore obsolete tty parameter
end
iopts.merge!( hash_arg )
if !iopts[:fallback_application_name]
iopts[:fallback_application_name] = $0.sub( /^(.{30}).{4,}(.{30})$/ ){ $1+"..."+$2 }
end
return connect_hash_to_string(iopts)
end
Check server status.
See PG::Connection.new
for a description of the parameters.
Returns one of:
PQPING_OK
server is accepting connections
PQPING_REJECT
server is alive but rejecting connections
PQPING_NO_RESPONSE
could not establish connection
PQPING_NO_ATTEMPT
connection not attempted (bad params)
# File lib/pg/connection.rb, line 788
def ping(*args)
if Fiber.respond_to?(:scheduler) && Fiber.scheduler
# Run PQping in a second thread to avoid blocking of the scheduler.
# Unfortunately there's no nonblocking way to run ping.
Thread.new { sync_ping(*args) }.value
else
sync_ping(*args)
end
end
Quote a single value
for use in a connection-parameter string.
# File lib/pg/connection.rb, line 37
def self.quote_connstr( value )
return "'" + value.to_s.gsub( /[\\']/ ) {|m| '\\' + m } + "'"
end
Returns a string that is safe for inclusion in a SQL query as an identifier. Note: this is not a quote function for values, but for identifiers.
For example, in a typical SQL query: SELECT FOO FROM MYTABLE
The identifier FOO
is folded to lower case, so it actually means foo
. If you really want to access the case-sensitive field name FOO
, use this function like conn.quote_ident('FOO')
, which will return "FOO"
(with double-quotes). PostgreSQL will see the double-quotes, and it will not fold to lower case.
Similarly, this function also protects against special characters, and other things that might allow SQL injection if the identifier comes from an untrusted source.
If the parameter is an Array, then all it’s values are separately quoted and then joined by a “.” character. This can be used for identifiers in the form “schema”.“table”.“column” .
This method is functional identical to the encoder PG::TextEncoder::Identifier
.
If the instance method form is used and the input string character encoding is different to the connection encoding, then the string is converted to this encoding, so that the returned string is always encoded as PG::Connection#internal_encoding
.
In the singleton form (PG::Connection.quote_ident
) the character encoding of the result string is set to the character encoding of the input string.
static VALUE
pgconn_s_quote_ident(VALUE self, VALUE str_or_array)
{
VALUE ret;
int enc_idx;
if( rb_obj_is_kind_of(self, rb_cPGconn) ){
enc_idx = pg_get_connection(self)->enc_idx;
}else{
enc_idx = RB_TYPE_P(str_or_array, T_STRING) ? ENCODING_GET( str_or_array ) : rb_ascii8bit_encindex();
}
pg_text_enc_identifier(NULL, str_or_array, NULL, &ret, enc_idx);
return ret;
}
static VALUE
pgconn_s_sync_connect(int argc, VALUE *argv, VALUE klass)
{
t_pg_connection *this;
VALUE conninfo;
VALUE self = pgconn_s_allocate( klass );
this = pg_get_connection( self );
conninfo = rb_funcall2( rb_cPGconn, rb_intern("parse_connect_args"), argc, argv );
this->pgconn = gvl_PQconnectdb(StringValueCStr(conninfo));
if(this->pgconn == NULL)
rb_raise(rb_ePGerror, "PQconnectdb() unable to allocate PGconn structure");
if (PQstatus(this->pgconn) == CONNECTION_BAD)
pg_raise_conn_error( rb_eConnectionBad, self, "%s", PQerrorMessage(this->pgconn));
pgconn_set_default_encoding( self );
if (rb_block_given_p()) {
return rb_ensure(rb_yield, self, pgconn_finish, self);
}
return self;
}
static VALUE
pgconn_s_sync_ping( int argc, VALUE *argv, VALUE klass )
{
PGPing ping;
VALUE conninfo;
conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
ping = gvl_PQping( StringValueCStr(conninfo) );
return INT2FIX((int)ping);
}
Converts an escaped string representation of binary data into binary data — the reverse of escape_bytea
. This is needed when retrieving bytea
data in text format, but not when retrieving it in binary format.
static VALUE
pgconn_s_unescape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t to_len;
VALUE ret;
UNUSED( self );
Check_Type(str, T_STRING);
from = (unsigned char*)StringValueCStr(str);
to = PQunescapeBytea(from, &to_len);
ret = rb_str_new((char*)to, to_len);
PQfreemem(to);
return ret;
}
Retrieve information about the portal portal_name.
See also corresponding libpq function.
Retrieve information about the prepared statement statement_name.
See also corresponding libpq function.
Sends SQL query request specified by sql to PostgreSQL. On success, it returns a PG::Result
instance with all result rows and columns. On failure, it raises a PG::Error
.
For backward compatibility, if you pass more than one parameter to this method, it will call exec_params
for you. New code should explicitly use exec_params
if argument placeholders are used.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec
returns the value of the block.
exec
is an alias for async_exec
which is almost identical to sync_exec
. sync_exec
is implemented on the simpler synchronous command processing API of libpq, whereas async_exec
is implemented on the asynchronous API and on ruby’s IO mechanisms. Only async_exec
is compatible to Fiber.scheduler
based asynchronous IO processing introduced in ruby-3.0. Both methods ensure that other threads can process while waiting for the server to complete the request, but sync_exec
blocks all signals to be processed until the query is finished. This is most notably visible by a delayed reaction to Control+C. It’s not recommended to use explicit sync or async variants but exec
instead, unless you have a good reason to do so.
See also corresponding libpq function.
Sends SQL query request specified by sql
to PostgreSQL using placeholders for parameters.
Returns a PG::Result
instance on success. On failure, it raises a PG::Error
.
params
is an array of the bind parameters for the SQL query. Each element of the params
array may be either:
a hash of the form: {:value => String (value of bind parameter) :type => Integer (oid of type of bind parameter) :format => Integer (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :type => 0, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params
array is bound to $1, the 1st element is bound to $2, etc. nil
is treated as NULL
.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
The optional result_format
should be 0 for text results, 1 for binary.
type_map
can be a PG::TypeMap
derivation (such as PG::BasicTypeMapForQueries
). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec
returns the value of the block.
The primary advantage of exec_params
over exec
is that parameter values can be separated from the command string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike exec
, exec_params
allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) This is a limitation of the underlying protocol, but has some usefulness as an extra defense against SQL-injection attacks.
See also corresponding libpq function.
Execute prepared named statement specified by statement_name. Returns a PG::Result
instance on success. On failure, it raises a PG::Error
.
params
is an array of the optional bind parameters for the SQL query. Each element of the params
array may be either:
a hash of the form: {:value => String (value of bind parameter) :format => Integer (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params
array is bound to $1, the 1st element is bound to $2, etc. nil
is treated as NULL
.
The optional result_format
should be 0 for text results, 1 for binary.
type_map
can be a PG::TypeMap
derivation (such as PG::BasicTypeMapForQueries
). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec_prepared
returns the value of the block.
See also corresponding libpq function.
Attempts to flush any queued output data to the server. Returns true
if data is successfully flushed, false
if not. It can only return false
if connection is in nonblocking mode. Raises PG::Error
if some other failure occurred.
This function retrieves all available results on the current connection (from previously issued asynchronous commands like +send_query()+) and returns the last non-NULL result, or nil
if no results are available.
If the last result contains a bad result_status, an appropriate exception is raised.
This function is similar to get_result
except that it is designed to get one and only one result and that it checks the result state.
Prepares statement sql with name name to be executed later. Returns a PG::Result
instance on success. On failure, it raises a PG::Error
.
param_types
is an optional parameter to specify the Oids of the types of the parameters.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query.
See also corresponding libpq function.
Sends SQL query request specified by sql to PostgreSQL. On success, it returns a PG::Result
instance with all result rows and columns. On failure, it raises a PG::Error
.
For backward compatibility, if you pass more than one parameter to this method, it will call exec_params
for you. New code should explicitly use exec_params
if argument placeholders are used.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec
returns the value of the block.
exec
is an alias for async_exec
which is almost identical to sync_exec
. sync_exec
is implemented on the simpler synchronous command processing API of libpq, whereas async_exec
is implemented on the asynchronous API and on ruby’s IO mechanisms. Only async_exec
is compatible to Fiber.scheduler
based asynchronous IO processing introduced in ruby-3.0. Both methods ensure that other threads can process while waiting for the server to complete the request, but sync_exec
blocks all signals to be processed until the query is finished. This is most notably visible by a delayed reaction to Control+C. It’s not recommended to use explicit sync or async variants but exec
instead, unless you have a good reason to do so.
See also corresponding libpq function.
Sets the client encoding to the encoding String.
Returns the key of the backend server process for this connection. This key can be used to cancel queries on the server.
static VALUE
pgconn_backend_key(VALUE self)
{
int be_key;
struct pg_cancel *cancel;
PGconn *conn = pg_get_pgconn(self);
cancel = (struct pg_cancel*)PQgetCancel(conn);
if(cancel == NULL)
pg_raise_conn_error( rb_ePGerror, self, "Invalid connection!");
if( cancel->be_pid != PQbackendPID(conn) )
rb_raise(rb_ePGerror,"Unexpected binary struct layout - please file a bug report at ruby-pg!");
be_key = cancel->be_key;
PQfreeCancel(cancel);
return INT2NUM(be_key);
}
Returns the process ID of the backend server process for this connection. Note that this is a PID on database server host.
static VALUE
pgconn_backend_pid(VALUE self)
{
return INT2NUM(PQbackendPID(pg_get_pgconn(self)));
}
Blocks until the server is no longer busy, or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns false
if timeout is reached, true
otherwise.
If true
is returned, conn.is_busy
will return false
and conn.get_result
will not block.
VALUE
pgconn_block( int argc, VALUE *argv, VALUE self ) {
struct timeval timeout;
struct timeval *ptimeout = NULL;
VALUE timeout_in;
double timeout_sec;
void *ret;
if ( rb_scan_args(argc, argv, "01", &timeout_in) == 1 ) {
timeout_sec = NUM2DBL( timeout_in );
timeout.tv_sec = (time_t)timeout_sec;
timeout.tv_usec = (suseconds_t)((timeout_sec - (long)timeout_sec) * 1e6);
ptimeout = &timeout;
}
ret = wait_socket_readable( self, ptimeout, get_result_readable);
if( !ret )
return Qfalse;
return Qtrue;
}
Requests cancellation of the command currently being processed.
Returns nil
on success, or a string containing the error message if a failure occurs.
# File lib/pg/connection.rb, line 485
def cancel
be_pid = backend_pid
be_key = backend_key
cancel_request = [0x10, 1234, 5678, be_pid, be_key].pack("NnnNN")
if Fiber.respond_to?(:scheduler) && Fiber.scheduler && RUBY_PLATFORM =~ /mingw|mswin/
# Ruby's nonblocking IO is not really supported on Windows.
# We work around by using threads and explicit calls to wait_readable/wait_writable.
cl = Thread.new(socket_io.remote_address) { |ra| ra.connect }.value
begin
cl.write_nonblock(cancel_request)
rescue IO::WaitReadable, Errno::EINTR
cl.wait_writable
retry
end
begin
cl.read_nonblock(1)
rescue IO::WaitReadable, Errno::EINTR
cl.wait_readable
retry
rescue EOFError
end
elsif RUBY_ENGINE == 'truffleruby'
begin
cl = socket_io.remote_address.connect
rescue NotImplementedError
# Workaround for truffleruby < 21.3.0
cl2 = Socket.for_fd(socket_io.fileno)
cl2.autoclose = false
adr = cl2.remote_address
if adr.ip?
cl = TCPSocket.new(adr.ip_address, adr.ip_port)
cl.autoclose = false
else
cl = UNIXSocket.new(adr.unix_path)
cl.autoclose = false
end
end
cl.write(cancel_request)
cl.read(1)
else
cl = socket_io.remote_address.connect
# Send CANCEL_REQUEST_CODE and parameters
cl.write(cancel_request)
# Wait for the postmaster to close the connection, which indicates that it's processed the request.
cl.read(1)
end
cl.close
nil
rescue SystemCallError => err
err.to_s
end
Sets the client encoding to the encoding String.
Returns an array of Hashes with connection defaults. See ::conndefaults
for details.
# File lib/pg/connection.rb, line 252
def conndefaults
return self.class.conndefaults
end
Returns a Hash with connection defaults. See ::conndefaults_hash
for details.
# File lib/pg/connection.rb, line 268
def conndefaults_hash
return self.class.conndefaults_hash
end
Returns one of:
PGRES_POLLING_READING
wait until the socket is ready to read
PGRES_POLLING_WRITING
wait until the socket is ready to write
PGRES_POLLING_FAILED
the asynchronous connection has failed
PGRES_POLLING_OK
the asynchronous connection is ready
Example:
require "io/wait" conn = PG::Connection.connect_start(dbname: 'mydatabase') status = conn.connect_poll while(status != PG::PGRES_POLLING_OK) do # do some work while waiting for the connection to complete if(status == PG::PGRES_POLLING_READING) unless conn.socket_io.wait_readable(10.0) raise "Asynchronous connection timed out!" end elsif(status == PG::PGRES_POLLING_WRITING) unless conn.socket_io.wait_writable(10.0) raise "Asynchronous connection timed out!" end end status = conn.connect_poll end # now conn.status == CONNECTION_OK, and connection # is ready.
static VALUE
pgconn_connect_poll(VALUE self)
{
PostgresPollingStatusType status;
status = gvl_PQconnectPoll(pg_get_pgconn(self));
pgconn_close_socket_io(self);
return INT2FIX((int)status);
}
Returns true
if the authentication method required a password, but none was available. false
otherwise.
static VALUE
pgconn_connection_needs_password(VALUE self)
{
return PQconnectionNeedsPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
Returns true
if the authentication method used a caller-supplied password, false
otherwise.
static VALUE
pgconn_connection_used_password(VALUE self)
{
return PQconnectionUsedPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
Returns the connection options used by a live connection.
Available since PostgreSQL-9.3
static VALUE
pgconn_conninfo( VALUE self )
{
PGconn *conn = pg_get_pgconn(self);
PQconninfoOption *options = PQconninfo( conn );
VALUE array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
return array;
}
Return the Postgres connection info structure as a Hash keyed by option keyword (as a Symbol).
See also conninfo
# File lib/pg/connection.rb, line 276
def conninfo_hash
return self.conninfo.each_with_object({}) do |info, hash|
hash[ info[:keyword].to_sym ] = info[:val]
end
end
If input is available from the server, consume it. After calling consume_input
, you can check is_busy
or notifies to see if the state has changed.
static VALUE
pgconn_consume_input(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
/* returns 0 on error */
if(PQconsumeInput(conn) == 0) {
pgconn_close_socket_io(self);
pg_raise_conn_error( rb_eConnectionBad, self, "%s", PQerrorMessage(conn));
}
return Qnil;
}
Execute a copy process for transferring data to or from the server.
This issues the SQL COPY command via exec
. The response to this (if there is no error in the command) is a PG::Result
object that is passed to the block, bearing a status code of PGRES_COPY_OUT or PGRES_COPY_IN (depending on the specified copy direction). The application should then use put_copy_data
or get_copy_data
to receive or transmit data rows and should return from the block when finished.
copy_data
returns another PG::Result
object when the data transfer is complete. An exception is raised if some problem was encountered, so it isn’t required to make use of any of them. At this point further SQL commands can be issued via exec
. (It is not possible to execute other SQL commands using the same connection while the COPY operation is in progress.)
This method ensures, that the copy process is properly terminated in case of client side or server side failures. Therefore, in case of blocking mode of operation, copy_data
is preferred to raw calls of put_copy_data
, get_copy_data
and put_copy_end
.
coder can be a PG::Coder
derivation (typically PG::TextEncoder::CopyRow
or PG::TextDecoder::CopyRow
). This enables encoding of data fields given to put_copy_data
or decoding of fields received by get_copy_data
.
Example with CSV input format:
conn.exec "create table my_table (a text,b text,c text,d text)" conn.copy_data "COPY my_table FROM STDIN CSV" do conn.put_copy_data "some,data,to,copy\n" conn.put_copy_data "more,data,to,copy\n" end
This creates my_table
and inserts two CSV rows.
The same with text format encoder PG::TextEncoder::CopyRow
and Array input:
enco = PG::TextEncoder::CopyRow.new conn.copy_data "COPY my_table FROM STDIN", enco do conn.put_copy_data ['some', 'data', 'to', 'copy'] conn.put_copy_data ['more', 'data', 'to', 'copy'] end
Example with CSV output format:
conn.copy_data "COPY my_table TO STDOUT CSV" do while row=conn.get_copy_data p row end end
This prints all rows of my_table
to stdout:
"some,data,to,copy\n" "more,data,to,copy\n"
The same with text format decoder PG::TextDecoder::CopyRow
and Array output:
deco = PG::TextDecoder::CopyRow.new conn.copy_data "COPY my_table TO STDOUT", deco do while row=conn.get_copy_data p row end end
This receives all rows of my_table
as ruby array:
["some", "data", "to", "copy"] ["more", "data", "to", "copy"]
# File lib/pg/connection.rb, line 163
def copy_data( sql, coder=nil )
raise PG::NotInBlockingMode.new("copy_data can not be used in nonblocking mode", connection: self) if nonblocking?
res = exec( sql )
case res.result_status
when PGRES_COPY_IN
begin
if coder
old_coder = self.encoder_for_put_copy_data
self.encoder_for_put_copy_data = coder
end
yield res
rescue Exception => err
errmsg = "%s while copy data: %s" % [ err.class.name, err.message ]
put_copy_end( errmsg )
get_result
raise
else
put_copy_end
get_last_result
ensure
self.encoder_for_put_copy_data = old_coder if coder
end
when PGRES_COPY_OUT
begin
if coder
old_coder = self.decoder_for_get_copy_data
self.decoder_for_get_copy_data = coder
end
yield res
rescue Exception => err
cancel
begin
while get_copy_data
end
rescue PG::Error
# Ignore error in cleanup to avoid losing original exception
end
while get_result
end
raise err
else
res = get_last_result
if !res || res.result_status != PGRES_COMMAND_OK
while get_copy_data
end
while get_result
end
raise PG::NotAllCopyDataRetrieved.new("Not all COPY data retrieved", connection: self)
end
res
ensure
self.decoder_for_get_copy_data = old_coder if coder
end
else
raise ArgumentError, "SQL command is no COPY statement: #{sql}"
end
end
Returns the connected database name.
static VALUE
pgconn_db(VALUE self)
{
char *db = PQdb(pg_get_pgconn(self));
if (!db) return Qnil;
return rb_str_new2(db);
}
Returns the default coder object that is currently set for type casting of received data by get_copy_data
.
Returns either:
a kind of PG::Coder
nil
- type encoding is disabled, returned data will be a String.
static VALUE
pgconn_decoder_for_get_copy_data_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->decoder_for_get_copy_data;
}
Set the default coder that is used for type casting of received data by get_copy_data
.
decoder
can be:
a kind of PG::Coder
nil
- disable type decoding, returned data will be a String.
static VALUE
pgconn_decoder_for_get_copy_data_set(VALUE self, VALUE decoder)
{
t_pg_connection *this = pg_get_connection( self );
if( decoder != Qnil ){
t_pg_coder *co;
UNUSED(co);
/* Check argument type */
TypedData_Get_Struct(decoder, t_pg_coder, &pg_coder_type, co);
}
this->decoder_for_get_copy_data = decoder;
return decoder;
}
Retrieve information about the portal portal_name.
See also corresponding libpq function.
static VALUE
pgconn_async_describe_portal(VALUE self, VALUE portal)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_describe_portal( self, portal );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
Retrieve information about the prepared statement statement_name.
See also corresponding libpq function.
static VALUE
pgconn_async_describe_prepared(VALUE self, VALUE stmt_name)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_describe_prepared( self, stmt_name );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
Silently discard any prior query result that application didn’t eat. This is done prior of Connection#exec
and sibling methods and can be called explicitly when using the async API.
static VALUE
pgconn_discard_results(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
VALUE socket_io;
if( PQtransactionStatus(conn) == PQTRANS_IDLE ) {
return Qnil;
}
socket_io = pgconn_socket_io(self);
for(;;) {
PGresult *cur;
int status;
/* pgconn_block() raises an exception in case of errors.
* To avoid this call pg_rb_io_wait() and PQconsumeInput() without rb_raise().
*/
while( gvl_PQisBusy(conn) ){
pg_rb_io_wait(socket_io, RB_INT2NUM(PG_RUBY_IO_READABLE), Qnil);
if ( PQconsumeInput(conn) == 0 ) {
pgconn_close_socket_io(self);
return Qfalse;
}
}
cur = gvl_PQgetResult(conn);
if( cur == NULL) break;
status = PQresultStatus(cur);
PQclear(cur);
if (status == PGRES_COPY_IN){
gvl_PQputCopyEnd(conn, "COPY terminated by new PQexec");
}
if (status == PGRES_COPY_OUT){
for(;;) {
char *buffer = NULL;
int st = gvl_PQgetCopyData(conn, &buffer, 1);
if( st == 0 ) {
/* would block -> wait for readable data */
pg_rb_io_wait(socket_io, RB_INT2NUM(PG_RUBY_IO_READABLE), Qnil);
if ( PQconsumeInput(conn) == 0 ) {
pgconn_close_socket_io(self);
return Qfalse;
}
} else if( st > 0 ) {
/* some data retrieved -> discard it */
PQfreemem(buffer);
} else {
/* no more data */
break;
}
}
}
}
return Qtrue;
}
Returns the default coder object that is currently set for type casting of parameters to put_copy_data
.
Returns either:
a kind of PG::Coder
nil
- type encoding is disabled, data must be a String.
static VALUE
pgconn_encoder_for_put_copy_data_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->encoder_for_put_copy_data;
}
Set the default coder that is used for type casting of parameters to put_copy_data
.
encoder
can be:
a kind of PG::Coder
nil
- disable type encoding, data must be a String.
static VALUE
pgconn_encoder_for_put_copy_data_set(VALUE self, VALUE encoder)
{
t_pg_connection *this = pg_get_connection( self );
if( encoder != Qnil ){
t_pg_coder *co;
UNUSED(co);
/* Check argument type */
TypedData_Get_Struct(encoder, t_pg_coder, &pg_coder_type, co);
}
this->encoder_for_put_copy_data = encoder;
return encoder;
}
This function is intended to be used by client applications that wish to send commands like ALTER USER joe PASSWORD 'pwd'
. It is good practice not to send the original cleartext password in such a command, because it might be exposed in command logs, activity displays, and so on. Instead, use this function to convert the password to encrypted form before it is sent.
The password
and username
arguments are the cleartext password, and the SQL name of the user it is for. algorithm
specifies the encryption algorithm to use to encrypt the password. Currently supported algorithms are md5
and scram-sha-256
(on
and off
are also accepted as aliases for md5
, for compatibility with older server versions). Note that support for scram-sha-256
was introduced in PostgreSQL version 10, and will not work correctly with older server versions. If algorithm is omitted or nil
, this function will query the server for the current value of the password_encryption
setting. That can block, and will fail if the current transaction is aborted, or if the connection is busy executing another query. If you wish to use the default algorithm for the server but want to avoid blocking, query password_encryption
yourself before calling encrypt_password
, and pass that value as the algorithm.
Return value is the encrypted password. The caller can assume the string doesn’t contain any special characters that would require escaping.
Available since PostgreSQL-10. See also corresponding libpq function.
# File lib/pg/connection.rb, line 458
def encrypt_password( password, username, algorithm=nil )
algorithm ||= exec("SHOW password_encryption").getvalue(0,0)
sync_encrypt_password(password, username, algorithm)
end
Causes a connection to enter pipeline mode if it is currently idle or already in pipeline mode.
Raises PG::Error
and has no effect if the connection is not currently idle, i.e., it has a result ready, or it is waiting for more input from the server, etc. This function does not actually send anything to the server, it just changes the libpq connection state.
Available since PostgreSQL-14
static VALUE
pgconn_enter_pipeline_mode(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = PQenterPipelineMode(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
Returns the error message most recently generated by an operation on the connection.
Nearly all libpq functions will set a message for conn.error_message if they fail. Note that by libpq convention, a nonempty error_message
result can consist of multiple lines, and will include a trailing newline.
static VALUE
pgconn_error_message(VALUE self)
{
char *error = PQerrorMessage(pg_get_pgconn(self));
if (!error) return Qnil;
return rb_str_new2(error);
}
Returns a SQL-safe version of the String str. This is the preferred way to make strings safe for inclusion in SQL queries.
Consider using exec_params
, which avoids the need for passing values inside of SQL commands.
Character encoding of escaped string will be equal to client encoding of connection.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
See also convenience functions escape_literal
and escape_identifier
which also add proper quotes around the string.
Escapes binary data for use within an SQL command with the type bytea
.
Certain byte values must be escaped (but all byte values may be escaped) when used as part of a bytea
literal in an SQL statement. In general, to escape a byte, it is converted into the three digit octal number equal to the octet value, and preceded by two backslashes. The single quote (‘) and backslash () characters have special alternative escape sequences. escape_bytea
performs this operation, escaping only the minimally required bytes.
Consider using exec_params
, which avoids the need for passing values inside of SQL commands.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
static VALUE
pgconn_s_escape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t from_len, to_len;
VALUE ret;
Check_Type(str, T_STRING);
from = (unsigned char*)RSTRING_PTR(str);
from_len = RSTRING_LEN(str);
if ( rb_obj_is_kind_of(self, rb_cPGconn) ) {
to = PQescapeByteaConn(pg_get_pgconn(self), from, from_len, &to_len);
} else {
to = PQescapeBytea( from, from_len, &to_len);
}
ret = rb_str_new((char*)to, to_len - 1);
PQfreemem(to);
return ret;
}
Escape an arbitrary String str
as an identifier.
This method does the same as quote_ident
with a String argument, but it doesn’t support an Array argument and it makes use of libpq to process the string.
static VALUE
pgconn_escape_identifier(VALUE self, VALUE string)
{
t_pg_connection *this = pg_get_connection_safe( self );
char *escaped = NULL;
VALUE result = Qnil;
int enc_idx = this->enc_idx;
StringValueCStr(string);
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
escaped = PQescapeIdentifier(this->pgconn, RSTRING_PTR(string), RSTRING_LEN(string));
if (escaped == NULL)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
result = rb_str_new2(escaped);
PQfreemem(escaped);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
return result;
}
Escape an arbitrary String str
as a literal.
See also PG::TextEncoder::QuotedLiteral
for a type cast integrated version of this function.
static VALUE
pgconn_escape_literal(VALUE self, VALUE string)
{
t_pg_connection *this = pg_get_connection_safe( self );
char *escaped = NULL;
VALUE result = Qnil;
int enc_idx = this->enc_idx;
StringValueCStr(string);
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
escaped = PQescapeLiteral(this->pgconn, RSTRING_PTR(string), RSTRING_LEN(string));
if (escaped == NULL)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
result = rb_str_new2(escaped);
PQfreemem(escaped);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
return result;
}
Returns a SQL-safe version of the String str. This is the preferred way to make strings safe for inclusion in SQL queries.
Consider using exec_params
, which avoids the need for passing values inside of SQL commands.
Character encoding of escaped string will be equal to client encoding of connection.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
See also convenience functions escape_literal
and escape_identifier
which also add proper quotes around the string.
static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
size_t size;
int error;
VALUE result;
int enc_idx;
int singleton = !rb_obj_is_kind_of(self, rb_cPGconn);
StringValueCStr(string);
enc_idx = singleton ? ENCODING_GET(string) : pg_get_connection(self)->enc_idx;
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
result = rb_str_new(NULL, RSTRING_LEN(string) * 2 + 1);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
if( !singleton ) {
size = PQescapeStringConn(pg_get_pgconn(self), RSTRING_PTR(result),
RSTRING_PTR(string), RSTRING_LEN(string), &error);
if(error)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(pg_get_pgconn(self)));
} else {
size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
}
rb_str_set_len(result, size);
return result;
}
Sends SQL query request specified by sql to PostgreSQL. On success, it returns a PG::Result
instance with all result rows and columns. On failure, it raises a PG::Error
.
For backward compatibility, if you pass more than one parameter to this method, it will call exec_params
for you. New code should explicitly use exec_params
if argument placeholders are used.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec
returns the value of the block.
exec
is an alias for async_exec
which is almost identical to sync_exec
. sync_exec
is implemented on the simpler synchronous command processing API of libpq, whereas async_exec
is implemented on the asynchronous API and on ruby’s IO mechanisms. Only async_exec
is compatible to Fiber.scheduler
based asynchronous IO processing introduced in ruby-3.0. Both methods ensure that other threads can process while waiting for the server to complete the request, but sync_exec
blocks all signals to be processed until the query is finished. This is most notably visible by a delayed reaction to Control+C. It’s not recommended to use explicit sync or async variants but exec
instead, unless you have a good reason to do so.
See also corresponding libpq function.
static VALUE
pgconn_async_exec(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_query( argc, argv, self );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
Sends SQL query request specified by sql
to PostgreSQL using placeholders for parameters.
Returns a PG::Result
instance on success. On failure, it raises a PG::Error
.
params
is an array of the bind parameters for the SQL query. Each element of the params
array may be either:
a hash of the form: {:value => String (value of bind parameter) :type => Integer (oid of type of bind parameter) :format => Integer (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :type => 0, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params
array is bound to $1, the 1st element is bound to $2, etc. nil
is treated as NULL
.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
The optional result_format
should be 0 for text results, 1 for binary.
type_map
can be a PG::TypeMap
derivation (such as PG::BasicTypeMapForQueries
). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec
returns the value of the block.
The primary advantage of exec_params
over exec
is that parameter values can be separated from the command string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike exec
, exec_params
allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) This is a limitation of the underlying protocol, but has some usefulness as an extra defense against SQL-injection attacks.
See also corresponding libpq function.
static VALUE
pgconn_async_exec_params(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
/* If called with no or nil parameters, use PQsendQuery for compatibility */
if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
pg_deprecated(3, ("forwarding async_exec_params to async_exec is deprecated"));
pgconn_send_query( argc, argv, self );
} else {
pgconn_send_query_params( argc, argv, self );
}
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
Execute prepared named statement specified by statement_name. Returns a PG::Result
instance on success. On failure, it raises a PG::Error
.
params
is an array of the optional bind parameters for the SQL query. Each element of the params
array may be either:
a hash of the form: {:value => String (value of bind parameter) :format => Integer (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params
array is bound to $1, the 1st element is bound to $2, etc. nil
is treated as NULL
.
The optional result_format
should be 0 for text results, 1 for binary.
type_map
can be a PG::TypeMap
derivation (such as PG::BasicTypeMapForQueries
). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec_prepared
returns the value of the block.
See also corresponding libpq function.
static VALUE
pgconn_async_exec_prepared(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_query_prepared( argc, argv, self );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
Causes a connection to exit pipeline mode if it is currently in pipeline mode with an empty queue and no pending results.
Takes no action if not in pipeline mode. Raises PG::Error
if the current statement isn’t finished processing, or PQgetResult has not been called to collect results from all previously sent query.
Available since PostgreSQL-14
static VALUE
pgconn_exit_pipeline_mode(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = PQexitPipelineMode(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
Return the server_encoding
of the connected database as a Ruby Encoding object. The SQL_ASCII
encoding is mapped to to ASCII_8BIT
.
static VALUE
pgconn_external_encoding(VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
rb_encoding *enc = NULL;
const char *pg_encname = NULL;
pg_encname = PQparameterStatus( this->pgconn, "server_encoding" );
enc = pg_get_pg_encname_as_rb_encoding( pg_encname );
return rb_enc_from_encoding( enc );
}
Get type of field names.
See description at field_name_type=
static VALUE
pgconn_field_name_type_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
if( this->flags & PG_RESULT_FIELD_NAMES_SYMBOL ){
return sym_symbol;
} else if( this->flags & PG_RESULT_FIELD_NAMES_STATIC_SYMBOL ){
return sym_static_symbol;
} else {
return sym_string;
}
}
Set default type of field names of results retrieved by this connection. It can be set to one of:
:string
to use String based field names
:symbol
to use Symbol based field names
The default is :string
.
Settings the type of field names affects only future results.
See further description at PG::Result#field_name_type=
static VALUE
pgconn_field_name_type_set(VALUE self, VALUE sym)
{
t_pg_connection *this = pg_get_connection( self );
this->flags &= ~PG_RESULT_FIELD_NAMES_MASK;
if( sym == sym_symbol ) this->flags |= PG_RESULT_FIELD_NAMES_SYMBOL;
else if ( sym == sym_static_symbol ) this->flags |= PG_RESULT_FIELD_NAMES_STATIC_SYMBOL;
else if ( sym == sym_string );
else rb_raise(rb_eArgError, "invalid argument %+"PRIsVALUE, sym);
return sym;
}
Closes the backend connection.
static VALUE
pgconn_finish( VALUE self )
{
t_pg_connection *this = pg_get_connection_safe( self );
pgconn_close_socket_io( self );
PQfinish( this->pgconn );
this->pgconn = NULL;
return Qnil;
}
Returns true
if the backend connection has been closed.
static VALUE
pgconn_finished_p( VALUE self )
{
t_pg_connection *this = pg_get_connection( self );
if ( this->pgconn ) return Qfalse;
return Qtrue;
}
Attempts to flush any queued output data to the server. Returns true
if data is successfully flushed, false
if not. It can only return false
if connection is in nonblocking mode. Raises PG::Error
if some other failure occurred.
static VALUE
pgconn_async_flush(VALUE self)
{
while( pgconn_sync_flush(self) == Qfalse ){
/* wait for the socket to become read- or write-ready */
int events;
VALUE socket_io = pgconn_socket_io(self);
events = RB_NUM2INT(pg_rb_io_wait(socket_io, RB_INT2NUM(PG_RUBY_IO_READABLE | PG_RUBY_IO_WRITABLE), Qnil));
if (events & PG_RUBY_IO_READABLE)
pgconn_consume_input(self);
}
return Qtrue;
}
Returns the client encoding as a String.
static VALUE
pgconn_get_client_encoding(VALUE self)
{
char *encoding = (char *)pg_encoding_to_char(PQclientEncoding(pg_get_pgconn(self)));
return rb_str_new2(encoding);
}
Return one row of data, nil
if the copy is done, or false
if the call would block (only possible if nonblock is true).
If decoder is not set or nil
, data is returned as binary string.
If decoder is set to a PG::Coder
derivation, the return type depends on this decoder. PG::TextDecoder::CopyRow
decodes the received data fields from one row of PostgreSQL’s COPY text format to an Array of Strings. Optionally the decoder can type cast the single fields to various Ruby types in one step, if PG::TextDecoder::CopyRow#type_map
is set accordingly.
See also copy_data
.
# File lib/pg/connection.rb, line 337
def get_copy_data(async=false, decoder=nil)
if async
return sync_get_copy_data(async, decoder)
else
while (res=sync_get_copy_data(true, decoder)) == false
socket_io.wait_readable
consume_input
end
return res
end
end
This function retrieves all available results on the current connection (from previously issued asynchronous commands like +send_query()+) and returns the last non-NULL result, or nil
if no results are available.
If the last result contains a bad result_status, an appropriate exception is raised.
This function is similar to get_result
except that it is designed to get one and only one result and that it checks the result state.
static VALUE
pgconn_async_get_last_result(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
VALUE rb_pgresult = Qnil;
PGresult *cur, *prev;
cur = prev = NULL;
for(;;) {
int status;
/* wait for input (without blocking) before reading each result */
wait_socket_readable(self, NULL, get_result_readable);
cur = gvl_PQgetResult(conn);
if (cur == NULL)
break;
if (prev) PQclear(prev);
prev = cur;
status = PQresultStatus(cur);
if (status == PGRES_COPY_OUT || status == PGRES_COPY_IN || status == PGRES_COPY_BOTH)
break;
}
if (prev) {
rb_pgresult = pg_new_result( prev, self );
pg_result_check(rb_pgresult);
}
return rb_pgresult;
}
Blocks waiting for the next result from a call to send_query
(or another asynchronous command), and returns it. Returns nil
if no more results are available.
Note: call this function repeatedly until it returns nil
, or else you will not be able to issue further commands.
If the optional code block is given, it will be passed result as an argument, and the PG::Result
object will automatically be cleared when the block terminates. In this instance, conn.exec
returns the value of the block.
# File lib/pg/connection.rb, line 314
def get_result
block
sync_get_result
end
Returns the server host name of the active connection. This can be a host name, an IP address, or a directory path if the connection is via Unix socket. (The path case can be distinguished because it will always be an absolute path, beginning with /
.)
If the connection parameters specified both host and hostaddr, then host
will return the host information. If only hostaddr was specified, then that is returned. If multiple hosts were specified in the connection parameters, host
returns the host actually connected to.
If there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.
If multiple hosts were specified in the connection parameters, it is not possible to rely on the result of host
until the connection is established. The status of the connection can be checked using the function Connection#status
.
static VALUE
pgconn_host(VALUE self)
{
char *host = PQhost(pg_get_pgconn(self));
if (!host) return Qnil;
return rb_str_new2(host);
}
Returns the server IP address of the active connection. This can be the address that a host name resolved to, or an IP address provided through the hostaddr parameter. If there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.
static VALUE
pgconn_hostaddr(VALUE self)
{
char *host = PQhostaddr(pg_get_pgconn(self));
if (!host) return Qnil;
return rb_str_new2(host);
}
defined in Ruby 1.9 or later.
Returns:
an Encoding - client_encoding of the connection as a Ruby Encoding object.
nil - the client_encoding is ‘SQL_ASCII’
static VALUE
pgconn_internal_encoding(VALUE self)
{
PGconn *conn = pg_get_pgconn( self );
rb_encoding *enc = pg_conn_enc_get( conn );
if ( enc ) {
return rb_enc_from_encoding( enc );
} else {
return Qnil;
}
}
A wrapper of set_client_encoding
. defined in Ruby 1.9 or later.
value
can be one of:
an Encoding
a String - a name of Encoding
nil
- sets the client_encoding to SQL_ASCII.
static VALUE
pgconn_internal_encoding_set(VALUE self, VALUE enc)
{
if (NIL_P(enc)) {
pgconn_sync_set_client_encoding( self, rb_usascii_str_new_cstr("SQL_ASCII") );
return enc;
}
else if ( TYPE(enc) == T_STRING && strcasecmp("JOHAB", StringValueCStr(enc)) == 0 ) {
pgconn_sync_set_client_encoding(self, rb_usascii_str_new_cstr("JOHAB"));
return enc;
}
else {
rb_encoding *rbenc = rb_to_encoding( enc );
const char *name = pg_get_rb_encoding_as_pg_encoding( rbenc );
if ( gvl_PQsetClientEncoding(pg_get_pgconn( self ), name) == -1 ) {
VALUE server_encoding = pgconn_external_encoding( self );
rb_raise( rb_eEncCompatError, "incompatible character encodings: %s and %s",
rb_enc_name(rb_to_encoding(server_encoding)), name );
}
pgconn_set_internal_encoding_index( self );
return enc;
}
}
Returns true
if a command is busy, that is, if get_result
would block. Otherwise returns false
.
static VALUE
pgconn_is_busy(VALUE self)
{
return gvl_PQisBusy(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
Returns the blocking status of the database connection. Returns true
if the connection is set to nonblocking mode and false
if blocking.
# File lib/pg/connection.rb, line 385
def isnonblocking
false
end
Closes the postgres large object of lo_desc.
static VALUE
pgconn_loclose(VALUE self, VALUE in_lo_desc)
{
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
if(lo_close(conn,lo_desc) < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_close failed");
return Qnil;
}
Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PG::Error
.
static VALUE
pgconn_locreat(int argc, VALUE *argv, VALUE self)
{
Oid lo_oid;
int mode;
VALUE nmode;
PGconn *conn = pg_get_pgconn(self);
if (rb_scan_args(argc, argv, "01", &nmode) == 0)
mode = INV_READ;
else
mode = NUM2INT(nmode);
lo_oid = lo_creat(conn, mode);
if (lo_oid == 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_creat failed");
return UINT2NUM(lo_oid);
}
Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PG::Error
.
static VALUE
pgconn_locreate(VALUE self, VALUE in_lo_oid)
{
Oid ret, lo_oid;
PGconn *conn = pg_get_pgconn(self);
lo_oid = NUM2UINT(in_lo_oid);
ret = lo_create(conn, lo_oid);
if (ret == InvalidOid)
pg_raise_conn_error( rb_ePGerror, self, "lo_create failed");
return UINT2NUM(ret);
}
Saves a large object of oid to a file.
static VALUE
pgconn_loexport(VALUE self, VALUE lo_oid, VALUE filename)
{
PGconn *conn = pg_get_pgconn(self);
Oid oid;
Check_Type(filename, T_STRING);
oid = NUM2UINT(lo_oid);
if (lo_export(conn, oid, StringValueCStr(filename)) < 0) {
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
}
return Qnil;
}
Import a file to a large object. Returns a large object Oid.
On failure, it raises a PG::Error
.
static VALUE
pgconn_loimport(VALUE self, VALUE filename)
{
Oid lo_oid;
PGconn *conn = pg_get_pgconn(self);
Check_Type(filename, T_STRING);
lo_oid = lo_import(conn, StringValueCStr(filename));
if (lo_oid == 0) {
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
}
return UINT2NUM(lo_oid);
}
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET
, SEEK_CUR
, and SEEK_END
. (Or 0, 1, or 2.)
static VALUE
pgconn_lolseek(VALUE self, VALUE in_lo_desc, VALUE offset, VALUE whence)
{
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
int ret;
if((ret = lo_lseek(conn, lo_desc, NUM2INT(offset), NUM2INT(whence))) < 0) {
pg_raise_conn_error( rb_ePGerror, self, "lo_lseek failed");
}
return INT2FIX(ret);
}
Open a large object of oid. Returns a large object descriptor instance on success. The mode argument specifies the mode for the opened large object,which is either INV_READ
, or INV_WRITE
.
If mode is omitted, the default is INV_READ
.
static VALUE
pgconn_loopen(int argc, VALUE *argv, VALUE self)
{
Oid lo_oid;
int fd, mode;
VALUE nmode, selfid;
PGconn *conn = pg_get_pgconn(self);
rb_scan_args(argc, argv, "11", &selfid, &nmode);
lo_oid = NUM2UINT(selfid);
if(NIL_P(nmode))
mode = INV_READ;
else
mode = NUM2INT(nmode);
if((fd = lo_open(conn, lo_oid, mode)) < 0) {
pg_raise_conn_error( rb_ePGerror, self, "can't open large object: %s", PQerrorMessage(conn));
}
return INT2FIX(fd);
}
Attempts to read len bytes from large object lo_desc, returns resulting data.
static VALUE
pgconn_loread(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
int ret;
PGconn *conn = pg_get_pgconn(self);
int len = NUM2INT(in_len);
int lo_desc = NUM2INT(in_lo_desc);
VALUE str;
char *buffer;
if (len < 0)
pg_raise_conn_error( rb_ePGerror, self, "negative length %d given", len);
buffer = ALLOC_N(char, len);
if((ret = lo_read(conn, lo_desc, buffer, len)) < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_read failed");
if(ret == 0) {
xfree(buffer);
return Qnil;
}
str = rb_str_new(buffer, ret);
xfree(buffer);
return str;
}
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET
, SEEK_CUR
, and SEEK_END
. (Or 0, 1, or 2.)
Returns the current position of the large object lo_desc.
static VALUE
pgconn_lotell(VALUE self, VALUE in_lo_desc)
{
int position;
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
if((position = lo_tell(conn, lo_desc)) < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_tell failed");
return INT2FIX(position);
}
Truncates the large object lo_desc to size len.
static VALUE
pgconn_lotruncate(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
size_t len = NUM2INT(in_len);
if(lo_truncate(conn,lo_desc,len) < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_truncate failed");
return Qnil;
}
Unlinks (deletes) the postgres large object of oid.
static VALUE
pgconn_lounlink(VALUE self, VALUE in_oid)
{
PGconn *conn = pg_get_pgconn(self);
Oid oid = NUM2UINT(in_oid);
if(lo_unlink(conn,oid) < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_unlink failed");
return Qnil;
}
Writes the string buffer to the large object lo_desc. Returns the number of bytes written.
static VALUE
pgconn_lowrite(VALUE self, VALUE in_lo_desc, VALUE buffer)
{
int n;
PGconn *conn = pg_get_pgconn(self);
int fd = NUM2INT(in_lo_desc);
Check_Type(buffer, T_STRING);
if( RSTRING_LEN(buffer) < 0) {
pg_raise_conn_error( rb_ePGerror, self, "write buffer zero string");
}
if((n = lo_write(conn, fd, StringValuePtr(buffer),
RSTRING_LEN(buffer))) < 0) {
pg_raise_conn_error( rb_ePGerror, self, "lo_write failed: %s", PQerrorMessage(conn));
}
return INT2FIX(n);
}
Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PG::Error
.
Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PG::Error
.
Import a file to a large object. Returns a large object Oid.
On failure, it raises a PG::Error
.
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET
, SEEK_CUR
, and SEEK_END
. (Or 0, 1, or 2.)
Open a large object of oid. Returns a large object descriptor instance on success. The mode argument specifies the mode for the opened large object,which is either INV_READ
, or INV_WRITE
.
If mode is omitted, the default is INV_READ
.
Attempts to read len bytes from large object lo_desc, returns resulting data.
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET
, SEEK_CUR
, and SEEK_END
. (Or 0, 1, or 2.)
Writes the string buffer to the large object lo_desc. Returns the number of bytes written.
Constructs and empty PG::Result
with status status. status may be one of:
PGRES_EMPTY_QUERY
PGRES_COMMAND_OK
PGRES_TUPLES_OK
PGRES_COPY_OUT
PGRES_COPY_IN
PGRES_BAD_RESPONSE
PGRES_NONFATAL_ERROR
PGRES_FATAL_ERROR
PGRES_COPY_BOTH
PGRES_SINGLE_TUPLE
PGRES_PIPELINE_SYNC
PGRES_PIPELINE_ABORTED
static VALUE
pgconn_make_empty_pgresult(VALUE self, VALUE status)
{
PGresult *result;
VALUE rb_pgresult;
PGconn *conn = pg_get_pgconn(self);
result = PQmakeEmptyPGresult(conn, NUM2INT(status));
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
return rb_pgresult;
}
Returns a hash of the unprocessed notifications. If there is no unprocessed notifier, it returns nil
.
static VALUE
pgconn_notifies(VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGnotify *notification;
VALUE hash;
VALUE sym_relname, sym_be_pid, sym_extra;
VALUE relname, be_pid, extra;
sym_relname = ID2SYM(rb_intern("relname"));
sym_be_pid = ID2SYM(rb_intern("be_pid"));
sym_extra = ID2SYM(rb_intern("extra"));
notification = gvl_PQnotifies(this->pgconn);
if (notification == NULL) {
return Qnil;
}
hash = rb_hash_new();
relname = rb_str_new2(notification->relname);
be_pid = INT2NUM(notification->be_pid);
extra = rb_str_new2(notification->extra);
PG_ENCODING_SET_NOCHECK( relname, this->enc_idx );
PG_ENCODING_SET_NOCHECK( extra, this->enc_idx );
rb_hash_aset(hash, sym_relname, relname);
rb_hash_aset(hash, sym_be_pid, be_pid);
rb_hash_aset(hash, sym_extra, extra);
PQfreemem(notification);
return hash;
}
Blocks while waiting for notification(s), or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns nil
if timeout is reached, the name of the NOTIFY event otherwise. If used in block form, passes the name of the NOTIFY event
, the generating pid
and the optional payload
string into the block.
Returns backend option string.
static VALUE
pgconn_options(VALUE self)
{
char *options = PQoptions(pg_get_pgconn(self));
if (!options) return Qnil;
return rb_str_new2(options);
}
Returns the setting of parameter param_name, where param_name is one of
server_version
server_encoding
client_encoding
is_superuser
session_authorization
DateStyle
TimeZone
integer_datetimes
standard_conforming_strings
Returns nil if the value of the parameter is not known.
static VALUE
pgconn_parameter_status(VALUE self, VALUE param_name)
{
const char *ret = PQparameterStatus(pg_get_pgconn(self), StringValueCStr(param_name));
if(ret == NULL)
return Qnil;
else
return rb_str_new2(ret);
}
Returns the authenticated password.
static VALUE
pgconn_pass(VALUE self)
{
char *user = PQpass(pg_get_pgconn(self));
if (!user) return Qnil;
return rb_str_new2(user);
}
Returns the current pipeline mode status of the libpq connection.
PQpipelineStatus can return one of the following values:
PQ_PIPELINE_ON - The libpq connection is in pipeline mode.
PQ_PIPELINE_OFF - The libpq connection is not in pipeline mode.
PQ_PIPELINE_ABORTED - The libpq connection is in pipeline mode and an error occurred while processing the current pipeline. The aborted flag is cleared when PQgetResult returns a result of type PGRES_PIPELINE_SYNC.
Available since PostgreSQL-14
static VALUE
pgconn_pipeline_status(VALUE self)
{
int res = PQpipelineStatus(pg_get_pgconn(self));
return INT2FIX(res);
}
Marks a synchronization point in a pipeline by sending a sync message and flushing the send buffer. This serves as the delimiter of an implicit transaction and an error recovery point; see Section 34.5.1.3 of the PostgreSQL documentation.
Raises PG::Error
if the connection is not in pipeline mode or sending a sync message failed.
Available since PostgreSQL-14
static VALUE
pgconn_pipeline_sync(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = PQpipelineSync(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
Returns the connected server port number.
static VALUE
pgconn_port(VALUE self)
{
char* port = PQport(pg_get_pgconn(self));
return INT2NUM(atoi(port));
}
Prepares statement sql with name name to be executed later. Returns a PG::Result
instance on success. On failure, it raises a PG::Error
.
param_types
is an optional parameter to specify the Oids of the types of the parameters.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query.
See also corresponding libpq function.
static VALUE
pgconn_async_prepare(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_prepare( argc, argv, self );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
The 3.0 protocol will normally be used when communicating with PostgreSQL 7.4 or later servers; pre-7.4 servers support only protocol 2.0. (Protocol 1.0 is obsolete and not supported by libpq.)
static VALUE
pgconn_protocol_version(VALUE self)
{
return INT2NUM(PQprotocolVersion(pg_get_pgconn(self)));
}
Transmits buffer as copy data to the server. Returns true if the data was sent, false if it was not sent (false is only possible if the connection is in nonblocking mode, and this command would block).
encoder can be a PG::Coder
derivation (typically PG::TextEncoder::CopyRow
). This encodes the data fields given as buffer from an Array of Strings to PostgreSQL’s COPY text format inclusive proper escaping. Optionally the encoder can type cast the fields from various Ruby types in one step, if PG::TextEncoder::CopyRow#type_map
is set accordingly.
Raises an exception if an error occurs.
See also copy_data
.
# File lib/pg/connection.rb, line 409
def put_copy_data(buffer, encoder=nil)
until res=sync_put_copy_data(buffer, encoder)
res = flush
end
res
end
Sends end-of-data indication to the server.
error_message is an optional parameter, and if set, forces the COPY command to fail with the string error_message.
Returns true if the end-of-data was sent, false* if it was not sent (false is only possible if the connection is in nonblocking mode, and this command would block).
# File lib/pg/connection.rb, line 429
def put_copy_end(*args)
until sync_put_copy_end(*args)
flush
end
flush
end
Returns a string that is safe for inclusion in a SQL query as an identifier. Note: this is not a quote function for values, but for identifiers.
For example, in a typical SQL query: SELECT FOO FROM MYTABLE
The identifier FOO
is folded to lower case, so it actually means foo
. If you really want to access the case-sensitive field name FOO
, use this function like conn.quote_ident('FOO')
, which will return "FOO"
(with double-quotes). PostgreSQL will see the double-quotes, and it will not fold to lower case.
Similarly, this function also protects against special characters, and other things that might allow SQL injection if the identifier comes from an untrusted source.
If the parameter is an Array, then all it’s values are separately quoted and then joined by a “.” character. This can be used for identifiers in the form “schema”.“table”.“column” .
This method is functional identical to the encoder PG::TextEncoder::Identifier
.
If the instance method form is used and the input string character encoding is different to the connection encoding, then the string is converted to this encoding, so that the returned string is always encoded as PG::Connection#internal_encoding
.
In the singleton form (PG::Connection.quote_ident
) the character encoding of the result string is set to the character encoding of the input string.
static VALUE
pgconn_s_quote_ident(VALUE self, VALUE str_or_array)
{
VALUE ret;
int enc_idx;
if( rb_obj_is_kind_of(self, rb_cPGconn) ){
enc_idx = pg_get_connection(self)->enc_idx;
}else{
enc_idx = RB_TYPE_P(str_or_array, T_STRING) ? ENCODING_GET( str_or_array ) : rb_ascii8bit_encindex();
}
pg_text_enc_identifier(NULL, str_or_array, NULL, &ret, enc_idx);
return ret;
}
Resets the backend connection. This method closes the backend connection and tries to re-connect.
# File lib/pg/connection.rb, line 470
def reset
reset_start
async_connect_or_reset(:reset_poll)
self
end
Checks the status of a connection reset operation. See connect_start and connect_poll
for usage information and return values.
static VALUE
pgconn_reset_poll(VALUE self)
{
PostgresPollingStatusType status;
status = gvl_PQresetPoll(pg_get_pgconn(self));
pgconn_close_socket_io(self);
return INT2FIX((int)status);
}
Initiate a connection reset in a nonblocking manner. This will close the current connection and attempt to reconnect using the same connection parameters. Use reset_poll
to check the status of the connection reset.
static VALUE
pgconn_reset_start(VALUE self)
{
pgconn_close_socket_io( self );
if(gvl_PQresetStart(pg_get_pgconn(self)) == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "reset has failed");
return Qnil;
}
Asynchronously send command to the server. Does not block. Use in combination with conn.get_result
.
static VALUE
pgconn_send_describe_portal(VALUE self, VALUE portal)
{
t_pg_connection *this = pg_get_connection_safe( self );
/* returns 0 on failure */
if(gvl_PQsendDescribePortal(this->pgconn, pg_cstr_enc(portal, this->enc_idx)) == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "%s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
Asynchronously send command to the server. Does not block. Use in combination with conn.get_result
.
static VALUE
pgconn_send_describe_prepared(VALUE self, VALUE stmt_name)
{
t_pg_connection *this = pg_get_connection_safe( self );
/* returns 0 on failure */
if(gvl_PQsendDescribePrepared(this->pgconn, pg_cstr_enc(stmt_name, this->enc_idx)) == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "%s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
Sends a request for the server to flush its output buffer.
The server flushes its output buffer automatically as a result of Connection#pipeline_sync
being called, or on any request when not in pipeline mode. This function is useful to cause the server to flush its output buffer in pipeline mode without establishing a synchronization point. Note that the request is not itself flushed to the server automatically; use Connection#flush
if necessary.
Available since PostgreSQL-14
static VALUE
pgconn_send_flush_request(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = PQsendFlushRequest(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
Prepares statement sql with name name to be executed later. Sends prepare command asynchronously, and returns immediately. On failure, it raises a PG::Error
.
param_types
is an optional parameter to specify the Oids of the types of the parameters.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query.
static VALUE
pgconn_send_prepare(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
int result;
VALUE name, command, in_paramtypes;
VALUE param;
int i = 0;
int nParams = 0;
Oid *paramTypes = NULL;
const char *name_cstr;
const char *command_cstr;
int enc_idx = this->enc_idx;
rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
name_cstr = pg_cstr_enc(name, enc_idx);
command_cstr = pg_cstr_enc(command, enc_idx);
if(! NIL_P(in_paramtypes)) {
Check_Type(in_paramtypes, T_ARRAY);
nParams = (int)RARRAY_LEN(in_paramtypes);
paramTypes = ALLOC_N(Oid, nParams);
for(i = 0; i < nParams; i++) {
param = rb_ary_entry(in_paramtypes, i);
if(param == Qnil)
paramTypes[i] = 0;
else
paramTypes[i] = NUM2UINT(param);
}
}
result = gvl_PQsendPrepare(this->pgconn, name_cstr, command_cstr, nParams, paramTypes);
xfree(paramTypes);
if(result == 0) {
pg_raise_conn_error( rb_eUnableToSend, self, "%s", PQerrorMessage(this->pgconn));
}
pgconn_wait_for_flush( self );
return Qnil;
}
Sends SQL query request specified by sql to PostgreSQL for asynchronous processing, and immediately returns. On failure, it raises a PG::Error
.
For backward compatibility, if you pass more than one parameter to this method, it will call send_query_params
for you. New code should explicitly use send_query_params
if argument placeholders are used.
static VALUE
pgconn_send_query(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
/* If called with no or nil parameters, use PQexec for compatibility */
if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
if(gvl_PQsendQuery(this->pgconn, pg_cstr_enc(argv[0], this->enc_idx)) == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "%s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
pg_deprecated(2, ("forwarding async_exec to async_exec_params and send_query to send_query_params is deprecated"));
/* If called with parameters, and optionally result_format,
* use PQsendQueryParams
*/
return pgconn_send_query_params( argc, argv, self);
}
Sends SQL query request specified by sql to PostgreSQL for asynchronous processing, and immediately returns. On failure, it raises a PG::Error
.
params
is an array of the bind parameters for the SQL query. Each element of the params
array may be either:
a hash of the form: {:value => String (value of bind parameter) :type => Integer (oid of type of bind parameter) :format => Integer (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :type => 0, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params
array is bound to $1, the 1st element is bound to $2, etc. nil
is treated as NULL
.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
The optional result_format
should be 0 for text results, 1 for binary.
type_map
can be a PG::TypeMap
derivation (such as PG::BasicTypeMapForQueries
). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
static VALUE
pgconn_send_query_params(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
int result;
VALUE command, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
rb_scan_args(argc, argv, "22", &command, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 1;
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQsendQueryParams(this->pgconn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);
free_query_params( ¶msData );
if(result == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "%s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
Execute prepared named statement specified by statement_name asynchronously, and returns immediately. On failure, it raises a PG::Error
.
params
is an array of the optional bind parameters for the SQL query. Each element of the params
array may be either:
a hash of the form: {:value => String (value of bind parameter) :format => Integer (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params
array is bound to $1, the 1st element is bound to $2, etc. nil
is treated as NULL
.
The optional result_format
should be 0 for text results, 1 for binary.
type_map
can be a PG::TypeMap
derivation (such as PG::BasicTypeMapForQueries
). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
static VALUE
pgconn_send_query_prepared(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
int result;
VALUE name, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
rb_scan_args(argc, argv, "13", &name, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 0;
if(NIL_P(paramsData.params)) {
paramsData.params = rb_ary_new2(0);
}
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQsendQueryPrepared(this->pgconn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
resultFormat);
free_query_params( ¶msData );
if(result == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "%s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
The number is formed by converting the major, minor, and revision numbers into two-decimal-digit numbers and appending them together. For example, version 7.4.2 will be returned as 70402, and version 8.1 will be returned as 80100 (leading zeroes are not shown). Zero is returned if the connection is bad.
static VALUE
pgconn_server_version(VALUE self)
{
return INT2NUM(PQserverVersion(pg_get_pgconn(self)));
}
Sets the client encoding to the encoding String.
static VALUE
pgconn_async_set_client_encoding(VALUE self, VALUE encname)
{
VALUE query_format, query;
Check_Type(encname, T_STRING);
query_format = rb_str_new_cstr("set client_encoding to '%s'");
query = rb_funcall(query_format, rb_intern("%"), 1, encname);
pgconn_async_exec(1, &query, self);
pgconn_set_internal_encoding_index( self );
return Qnil;
}
If Ruby has its Encoding.default_internal set, set PostgreSQL’s client_encoding to match. Returns the new Encoding, or nil
if the default internal encoding wasn’t set.
static VALUE
pgconn_set_default_encoding( VALUE self )
{
PGconn *conn = pg_get_pgconn( self );
rb_encoding *enc;
const char *encname;
if (( enc = rb_default_internal_encoding() )) {
encname = pg_get_rb_encoding_as_pg_encoding( enc );
if ( pgconn_set_client_encoding_async(self, rb_str_new_cstr(encname)) != 0 )
rb_warning( "Failed to set the default_internal encoding to %s: '%s'",
encname, PQerrorMessage(conn) );
return rb_enc_from_encoding( enc );
} else {
pgconn_set_internal_encoding_index( self );
return Qnil;
}
}
Sets connection’s context display mode to context_visibility and returns the previous setting. Available settings are:
PQSHOW_CONTEXT_NEVER
PQSHOW_CONTEXT_ERRORS
PQSHOW_CONTEXT_ALWAYS
This mode controls whether the CONTEXT field is included in messages (unless the verbosity setting is TERSE, in which case CONTEXT is never shown). The NEVER mode never includes CONTEXT, while ALWAYS always includes it if available. In ERRORS mode (the default), CONTEXT fields are included only for error messages, not for notices and warnings.
Changing this mode does not affect the messages available from already-existing PG::Result
objects, only subsequently-created ones. (But see PG::Result#verbose_error_message
if you want to print a previous error with a different display mode.)
See also corresponding libpq function.
Available since PostgreSQL-9.6
static VALUE
pgconn_set_error_context_visibility(VALUE self, VALUE in_context_visibility)
{
PGconn *conn = pg_get_pgconn(self);
PGContextVisibility context_visibility = NUM2INT(in_context_visibility);
return INT2FIX(PQsetErrorContextVisibility(conn, context_visibility));
}
Sets connection’s verbosity to verbosity and returns the previous setting. Available settings are:
PQERRORS_TERSE
PQERRORS_DEFAULT
PQERRORS_VERBOSE
PQERRORS_SQLSTATE
Changing the verbosity does not affect the messages available from already-existing PG::Result
objects, only subsequently-created ones. (But see PG::Result#verbose_error_message
if you want to print a previous error with a different verbosity.)
See also corresponding libpq function.
static VALUE
pgconn_set_error_verbosity(VALUE self, VALUE in_verbosity)
{
PGconn *conn = pg_get_pgconn(self);
PGVerbosity verbosity = NUM2INT(in_verbosity);
return INT2FIX(PQsetErrorVerbosity(conn, verbosity));
}
See set_notice_receiver
for the description of what this and the notice_processor methods do.
This function takes a new block to act as the notice processor and returns the Proc object previously set, or nil
if it was previously the default. The block should accept a single String object.
If you pass no arguments, it will reset the handler to the default.
static VALUE
pgconn_set_notice_processor(VALUE self)
{
VALUE proc, old_proc;
t_pg_connection *this = pg_get_connection_safe( self );
/* If default_notice_processor is unset, assume that the current
* notice processor is the default, and save it to a global variable.
* This should not be a problem because the default processor is
* always the same, so won't vary among connections.
*/
if(default_notice_processor == NULL)
default_notice_processor = PQsetNoticeProcessor(this->pgconn, NULL, NULL);
old_proc = this->notice_receiver;
if( rb_block_given_p() ) {
proc = rb_block_proc();
PQsetNoticeProcessor(this->pgconn, gvl_notice_processor_proxy, (void *)self);
} else {
/* if no block is given, set back to default */
proc = Qnil;
PQsetNoticeProcessor(this->pgconn, default_notice_processor, NULL);
}
this->notice_receiver = proc;
return old_proc;
}
Notice and warning messages generated by the server are not returned by the query execution functions, since they do not imply failure of the query. Instead they are passed to a notice handling function, and execution continues normally after the handler returns. The default notice handling function prints the message on stderr
, but the application can override this behavior by supplying its own handling function.
For historical reasons, there are two levels of notice handling, called the notice receiver and notice processor. The default behavior is for the notice receiver to format the notice and pass a string to the notice processor for printing. However, an application that chooses to provide its own notice receiver will typically ignore the notice processor layer and just do all the work in the notice receiver.
This function takes a new block to act as the handler, which should accept a single parameter that will be a PG::Result
object, and returns the Proc object previously set, or nil
if it was previously the default.
If you pass no arguments, it will reset the handler to the default.
Note: The result
passed to the block should not be used outside of the block, since the corresponding C object could be freed after the block finishes.
static VALUE
pgconn_set_notice_receiver(VALUE self)
{
VALUE proc, old_proc;
t_pg_connection *this = pg_get_connection_safe( self );
/* If default_notice_receiver is unset, assume that the current
* notice receiver is the default, and save it to a global variable.
* This should not be a problem because the default receiver is
* always the same, so won't vary among connections.
*/
if(default_notice_receiver == NULL)
default_notice_receiver = PQsetNoticeReceiver(this->pgconn, NULL, NULL);
old_proc = this->notice_receiver;
if( rb_block_given_p() ) {
proc = rb_block_proc();
PQsetNoticeReceiver(this->pgconn, gvl_notice_receiver_proxy, (void *)self);
} else {
/* if no block is given, set back to default */
proc = Qnil;
PQsetNoticeReceiver(this->pgconn, default_notice_receiver, NULL);
}
this->notice_receiver = proc;
return old_proc;
}
To enter single-row mode, call this method immediately after a successful call of send_query
(or a sibling function). This mode selection is effective only for the currently executing query. Then call Connection#get_result
repeatedly, until it returns nil.
Each (but the last) received Result has exactly one row and a Result#result_status of PGRES_SINGLE_TUPLE. The last Result has zero rows and is used to indicate a successful execution of the query. All of these Result objects will contain the same row description data (column names, types, etc) that an ordinary Result object for the query would have.
Caution: While processing a query, the server may return some rows and then encounter an error, causing the query to be aborted. Ordinarily, pg discards any such rows and reports only the error. But in single-row mode, those rows will have already been returned to the application. Hence, the application will see some Result objects followed by an Error raised in get_result. For proper transactional behavior, the application must be designed to discard or undo whatever has been done with the previously-processed rows, if the query ultimately fails.
Example:
conn.send_query( "your SQL command" ) conn.set_single_row_mode loop do res = conn.get_result or break res.check res.each do |row| # do something with the received row end end
static VALUE
pgconn_set_single_row_mode(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
if( PQsetSingleRowMode(conn) == 0 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return self;
}
Sets the nonblocking status of the connection. In the blocking state, calls to send_query
will block until the message is sent to the server, but will not wait for the query results. In the nonblocking state, calls to send_query
will return an error if the socket is not ready for writing. Note: This function does not affect exec
, because that function doesn’t return until the server has processed the query and returned the results.
Returns nil
.
# File lib/pg/connection.rb, line 371
def setnonblocking(enabled)
singleton_class.async_send_api = !enabled
self.flush_data = !enabled
sync_setnonblocking(true)
end
This method is deprecated. Please use the more portable method socket_io
.
Returns the socket’s file descriptor for this connection. IO.for_fd()
can be used to build a proper IO object to the socket. If you do so, you will likely also want to set autoclose=false
on it to prevent Ruby from closing the socket to PostgreSQL if it goes out of scope. Alternatively, you can use socket_io
, which creates an IO that’s associated with the connection object itself, and so won’t go out of scope until the connection does.
Note: On Windows the file descriptor is not usable, since it can not be used to build a Ruby IO object.
static VALUE
pgconn_socket(VALUE self)
{
int sd;
pg_deprecated(4, ("conn.socket is deprecated and should be replaced by conn.socket_io"));
if( (sd = PQsocket(pg_get_pgconn(self))) < 0)
pg_raise_conn_error( rb_eConnectionBad, self, "PQsocket() can't get socket descriptor");
return INT2NUM(sd);
}
Fetch an IO object created from the Connection’s underlying socket. This object can be used per socket_io.wait_readable
, socket_io.wait_writable
or for IO.select
to wait for events while running asynchronous API calls. IO#wait_*able
is is Fiber.scheduler
compatible in contrast to IO.select
.
The IO object can change while the connection is established, but is memorized afterwards. So be sure not to cache the IO object, but repeat calling conn.socket_io
instead.
Using this method also works on Windows in contrast to using socket
. It also avoids the problem of the underlying connection being closed by Ruby when an IO created using IO.for_fd(conn.socket)
goes out of scope.
static VALUE
pgconn_socket_io(VALUE self)
{
int sd;
int ruby_sd;
t_pg_connection *this = pg_get_connection_safe( self );
VALUE cSocket;
VALUE socket_io = this->socket_io;
if ( !RTEST(socket_io) ) {
if( (sd = PQsocket(this->pgconn)) < 0){
pg_raise_conn_error( rb_eConnectionBad, self, "PQsocket() can't get socket descriptor");
}
#ifdef _WIN32
ruby_sd = rb_w32_wrap_io_handle((HANDLE)(intptr_t)sd, O_RDWR|O_BINARY|O_NOINHERIT);
if( ruby_sd == -1 )
pg_raise_conn_error( rb_eConnectionBad, self, "Could not wrap win32 socket handle");
this->ruby_sd = ruby_sd;
#else
ruby_sd = sd;
#endif
cSocket = rb_const_get(rb_cObject, rb_intern("BasicSocket"));
socket_io = rb_funcall( cSocket, rb_intern("for_fd"), 1, INT2NUM(ruby_sd));
/* Disable autoclose feature */
rb_funcall( socket_io, s_id_autoclose_set, 1, Qfalse );
this->socket_io = socket_io;
}
return socket_io;
}
Returns SSL-related information about the connection.
The list of available attributes varies depending on the SSL library being used, and the type of connection. If an attribute is not available, returns nil.
The following attributes are commonly available:
library
Name of the SSL implementation in use. (Currently, only “OpenSSL” is implemented)
protocol
SSL/TLS version in use. Common values are “SSLv2”, “SSLv3”, “TLSv1”, “TLSv1.1” and “TLSv1.2”, but an implementation may return other strings if some other protocol is used.
key_bits
Number of key bits used by the encryption algorithm.
cipher
A short name of the ciphersuite used, e.g. “DHE-RSA-DES-CBC3-SHA”. The names are specific to each SSL implementation.
compression
If SSL compression is in use, returns the name of the compression algorithm, or “on” if compression is used but the algorithm is not known. If compression is not in use, returns “off”.
See also ssl_attribute_names
and the corresponding libpq function.
Available since PostgreSQL-9.5
static VALUE
pgconn_ssl_attribute(VALUE self, VALUE attribute_name)
{
const char *p_attr;
p_attr = PQsslAttribute(pg_get_pgconn(self), StringValueCStr(attribute_name));
return p_attr ? rb_str_new_cstr(p_attr) : Qnil;
}
Return an array of SSL attribute names available.
See also ssl_attribute
Available since PostgreSQL-9.5
static VALUE
pgconn_ssl_attribute_names(VALUE self)
{
int i;
const char * const * p_list = PQsslAttributeNames(pg_get_pgconn(self));
VALUE ary = rb_ary_new();
for ( i = 0; p_list[i]; i++ ) {
rb_ary_push( ary, rb_str_new_cstr( p_list[i] ));
}
return ary;
}
Returns SSL-related information about the connection as key/value pairs
The available attributes varies depending on the SSL library being used, and the type of connection.
See also ssl_attribute
# File lib/pg/connection.rb, line 293
def ssl_attributes
ssl_attribute_names.each.with_object({}) do |n,h|
h[n] = ssl_attribute(n)
end
end
Returns true
if the connection uses SSL/TLS, false
if not.
Available since PostgreSQL-9.5
static VALUE
pgconn_ssl_in_use(VALUE self)
{
return PQsslInUse(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
Returns the status of the connection, which is one:
PG::Constants::CONNECTION_OK PG::Constants::CONNECTION_BAD
… and other constants of kind PG::Constants::CONNECTION_*
Example:
PG.constants.grep(/CONNECTION_/).find{|c| PG.const_get(c) == conn.status} # => :CONNECTION_OK
static VALUE
pgconn_status(VALUE self)
{
return INT2NUM(PQstatus(pg_get_pgconn(self)));
}
static VALUE
pgconn_sync_cancel(VALUE self)
{
char errbuf[256];
PGcancel *cancel;
VALUE retval;
int ret;
cancel = PQgetCancel(pg_get_pgconn(self));
if(cancel == NULL)
pg_raise_conn_error( rb_ePGerror, self, "Invalid connection!");
ret = gvl_PQcancel(cancel, errbuf, sizeof(errbuf));
if(ret == 1)
retval = Qnil;
else
retval = rb_str_new2(errbuf);
PQfreeCancel(cancel);
return retval;
}
This function has the same behavior as async_describe_portal
, but is implemented using the synchronous command processing API of libpq. See async_exec
for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but describe_portal
instead, unless you have a good reason to do so.
static VALUE
pgconn_sync_describe_portal(self, stmt_name)
VALUE self, stmt_name;
{
PGresult *result;
VALUE rb_pgresult;
t_pg_connection *this = pg_get_connection_safe( self );
const char *stmt;
if(NIL_P(stmt_name)) {
stmt = NULL;
}
else {
stmt = pg_cstr_enc(stmt_name, this->enc_idx);
}
result = gvl_PQdescribePortal(this->pgconn, stmt);
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
return rb_pgresult;
}
This function has the same behavior as async_describe_prepared
, but is implemented using the synchronous command processing API of libpq. See async_exec
for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but describe_prepared
instead, unless you have a good reason to do so.
static VALUE
pgconn_sync_describe_prepared(VALUE self, VALUE stmt_name)
{
PGresult *result;
VALUE rb_pgresult;
t_pg_connection *this = pg_get_connection_safe( self );
const char *stmt;
if(NIL_P(stmt_name)) {
stmt = NULL;
}
else {
stmt = pg_cstr_enc(stmt_name, this->enc_idx);
}
result = gvl_PQdescribePrepared(this->pgconn, stmt);
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
return rb_pgresult;
}
static VALUE
pgconn_sync_encrypt_password(int argc, VALUE *argv, VALUE self)
{
char *encrypted = NULL;
VALUE rval = Qnil;
VALUE password, username, algorithm;
PGconn *conn = pg_get_pgconn(self);
rb_scan_args( argc, argv, "21", &password, &username, &algorithm );
Check_Type(password, T_STRING);
Check_Type(username, T_STRING);
encrypted = gvl_PQencryptPasswordConn(conn, StringValueCStr(password), StringValueCStr(username), RTEST(algorithm) ? StringValueCStr(algorithm) : NULL);
if ( encrypted ) {
rval = rb_str_new2( encrypted );
PQfreemem( encrypted );
} else {
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
}
return rval;
}
This function has the same behavior as async_exec
, but is implemented using the synchronous command processing API of libpq. It’s not recommended to use explicit sync or async variants but exec
instead, unless you have a good reason to do so.
Both sync_exec
and async_exec
release the GVL while waiting for server response, so that concurrent threads will get executed. However async_exec
has two advantages:
async_exec
can be aborted by signals (like Ctrl-C), while exec
blocks signal processing until the query is answered.
Ruby VM gets notified about IO blocked operations and can pass them through Fiber.scheduler
. So only async_*
methods are compatible to event based schedulers like the async gem.
static VALUE
pgconn_sync_exec(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
/* If called with no or nil parameters, use PQexec for compatibility */
if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
VALUE query_str = argv[0];
result = gvl_PQexec(this->pgconn, pg_cstr_enc(query_str, this->enc_idx));
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
pg_deprecated(0, ("forwarding exec to exec_params is deprecated"));
/* Otherwise, just call #exec_params instead for backward-compatibility */
return pgconn_sync_exec_params( argc, argv, self );
}
This function has the same behavior as async_exec_params
, but is implemented using the synchronous command processing API of libpq. See async_exec
for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but exec_params
instead, unless you have a good reason to do so.
static VALUE
pgconn_sync_exec_params( int argc, VALUE *argv, VALUE self )
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
VALUE command, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
/* For compatibility we accept 1 to 4 parameters */
rb_scan_args(argc, argv, "13", &command, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 1;
/*
* For backward compatibility no or +nil+ for the second parameter
* is passed to #exec
*/
if ( NIL_P(paramsData.params) ) {
pg_deprecated(1, ("forwarding exec_params to exec is deprecated"));
return pgconn_sync_exec( 1, argv, self );
}
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQexecParams(this->pgconn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);
free_query_params( ¶msData );
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
This function has the same behavior as async_exec_prepared
, but is implemented using the synchronous command processing API of libpq. See async_exec
for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but exec_prepared
instead, unless you have a good reason to do so.
static VALUE
pgconn_sync_exec_prepared(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
VALUE name, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
rb_scan_args(argc, argv, "13", &name, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 0;
if(NIL_P(paramsData.params)) {
paramsData.params = rb_ary_new2(0);
}
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQexecPrepared(this->pgconn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
resultFormat);
free_query_params( ¶msData );
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult,
pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
static VALUE
pgconn_sync_flush(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int ret = PQflush(conn);
if(ret == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return (ret) ? Qfalse : Qtrue;
}
static VALUE
pgconn_sync_get_copy_data(int argc, VALUE *argv, VALUE self )
{
VALUE async_in;
VALUE result;
int ret;
char *buffer;
VALUE decoder;
t_pg_coder *p_coder = NULL;
t_pg_connection *this = pg_get_connection_safe( self );
rb_scan_args(argc, argv, "02", &async_in, &decoder);
if( NIL_P(decoder) ){
if( !NIL_P(this->decoder_for_get_copy_data) ){
p_coder = RTYPEDDATA_DATA( this->decoder_for_get_copy_data );
}
} else {
/* Check argument type and use argument decoder */
TypedData_Get_Struct(decoder, t_pg_coder, &pg_coder_type, p_coder);
}
ret = gvl_PQgetCopyData(this->pgconn, &buffer, RTEST(async_in));
if(ret == -2){ /* error */
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
}
if(ret == -1) { /* No data left */
return Qnil;
}
if(ret == 0) { /* would block */
return Qfalse;
}
if( p_coder ){
t_pg_coder_dec_func dec_func = pg_coder_dec_func( p_coder, p_coder->format );
result = dec_func( p_coder, buffer, ret, 0, 0, this->enc_idx );
} else {
result = rb_str_new(buffer, ret);
}
PQfreemem(buffer);
return result;
}
This function has the same behavior as async_get_last_result
, but is implemented using the synchronous command processing API of libpq. See async_exec
for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but get_last_result
instead, unless you have a good reason to do so.
static VALUE
pgconn_sync_get_last_result(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
VALUE rb_pgresult = Qnil;
PGresult *cur, *prev;
cur = prev = NULL;
while ((cur = gvl_PQgetResult(conn)) != NULL) {
int status;
if (prev) PQclear(prev);
prev = cur;
status = PQresultStatus(cur);
if (status == PGRES_COPY_OUT || status == PGRES_COPY_IN || status == PGRES_COPY_BOTH)
break;
}
if (prev) {
rb_pgresult = pg_new_result( prev, self );
pg_result_check(rb_pgresult);
}
return rb_pgresult;
}
static VALUE
pgconn_sync_get_result(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
PGresult *result;
VALUE rb_pgresult;
result = gvl_PQgetResult(conn);
if(result == NULL)
return Qnil;
rb_pgresult = pg_new_result(result, self);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult,
pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
static VALUE
pgconn_sync_isnonblocking(VALUE self)
{
return PQisnonblocking(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
This function has the same behavior as async_prepare
, but is implemented using the synchronous command processing API of libpq. See async_exec
for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but prepare
instead, unless you have a good reason to do so.
static VALUE
pgconn_sync_prepare(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
VALUE name, command, in_paramtypes;
VALUE param;
int i = 0;
int nParams = 0;
Oid *paramTypes = NULL;
const char *name_cstr;
const char *command_cstr;
int enc_idx = this->enc_idx;
rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
name_cstr = pg_cstr_enc(name, enc_idx);
command_cstr = pg_cstr_enc(command, enc_idx);
if(! NIL_P(in_paramtypes)) {
Check_Type(in_paramtypes, T_ARRAY);
nParams = (int)RARRAY_LEN(in_paramtypes);
paramTypes = ALLOC_N(Oid, nParams);
for(i = 0; i < nParams; i++) {
param = rb_ary_entry(in_paramtypes, i);
if(param == Qnil)
paramTypes[i] = 0;
else
paramTypes[i] = NUM2UINT(param);
}
}
result = gvl_PQprepare(this->pgconn, name_cstr, command_cstr, nParams, paramTypes);
xfree(paramTypes);
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
return rb_pgresult;
}
static VALUE
pgconn_sync_put_copy_data(int argc, VALUE *argv, VALUE self)
{
int ret;
int len;
t_pg_connection *this = pg_get_connection_safe( self );
VALUE value;
VALUE buffer = Qnil;
VALUE encoder;
VALUE intermediate;
t_pg_coder *p_coder = NULL;
rb_scan_args( argc, argv, "11", &value, &encoder );
if( NIL_P(encoder) ){
if( NIL_P(this->encoder_for_put_copy_data) ){
buffer = value;
} else {
p_coder = RTYPEDDATA_DATA( this->encoder_for_put_copy_data );
}
} else {
/* Check argument type and use argument encoder */
TypedData_Get_Struct(encoder, t_pg_coder, &pg_coder_type, p_coder);
}
if( p_coder ){
t_pg_coder_enc_func enc_func;
int enc_idx = this->enc_idx;
enc_func = pg_coder_enc_func( p_coder );
len = enc_func( p_coder, value, NULL, &intermediate, enc_idx);
if( len == -1 ){
/* The intermediate value is a String that can be used directly. */
buffer = intermediate;
} else {
buffer = rb_str_new(NULL, len);
len = enc_func( p_coder, value, RSTRING_PTR(buffer), &intermediate, enc_idx);
rb_str_set_len( buffer, len );
}
}
Check_Type(buffer, T_STRING);
ret = gvl_PQputCopyData(this->pgconn, RSTRING_PTR(buffer), RSTRING_LENINT(buffer));
if(ret == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
RB_GC_GUARD(intermediate);
RB_GC_GUARD(buffer);
return (ret) ? Qtrue : Qfalse;
}
static VALUE
pgconn_sync_put_copy_end(int argc, VALUE *argv, VALUE self)
{
VALUE str;
int ret;
const char *error_message = NULL;
t_pg_connection *this = pg_get_connection_safe( self );
if (rb_scan_args(argc, argv, "01", &str) == 0)
error_message = NULL;
else
error_message = pg_cstr_enc(str, this->enc_idx);
ret = gvl_PQputCopyEnd(this->pgconn, error_message);
if(ret == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
return (ret) ? Qtrue : Qfalse;
}
static VALUE
pgconn_sync_reset( VALUE self )
{
pgconn_close_socket_io( self );
gvl_PQreset( pg_get_pgconn(self) );
return self;
}
This function has the same behavior as async_set_client_encoding
, but is implemented using the synchronous command processing API of libpq. See async_exec
for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but set_client_encoding
instead, unless you have a good reason to do so.
static VALUE
pgconn_sync_set_client_encoding(VALUE self, VALUE str)
{
PGconn *conn = pg_get_pgconn( self );
Check_Type(str, T_STRING);
if ( (gvl_PQsetClientEncoding(conn, StringValueCStr(str))) == -1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
pgconn_set_internal_encoding_index( self );
return Qnil;
}
static VALUE
pgconn_sync_setnonblocking(VALUE self, VALUE state)
{
int arg;
PGconn *conn = pg_get_pgconn(self);
if(state == Qtrue)
arg = 1;
else if (state == Qfalse)
arg = 0;
else
rb_raise(rb_eArgError, "Boolean value expected");
if(PQsetnonblocking(conn, arg) == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
Enables tracing message passing between backend. The trace message will be written to the stream stream, which must implement a method fileno
that returns a writable file descriptor.
static VALUE
pgconn_trace(VALUE self, VALUE stream)
{
VALUE fileno;
FILE *new_fp;
int old_fd, new_fd;
VALUE new_file;
t_pg_connection *this = pg_get_connection_safe( self );
if(!rb_respond_to(stream,rb_intern("fileno")))
rb_raise(rb_eArgError, "stream does not respond to method: fileno");
fileno = rb_funcall(stream, rb_intern("fileno"), 0);
if(fileno == Qnil)
rb_raise(rb_eArgError, "can't get file descriptor from stream");
/* Duplicate the file descriptor and re-open
* it. Then, make it into a ruby File object
* and assign it to an instance variable.
* This prevents a problem when the File
* object passed to this function is closed
* before the connection object is. */
old_fd = NUM2INT(fileno);
new_fd = dup(old_fd);
new_fp = fdopen(new_fd, "w");
if(new_fp == NULL)
rb_raise(rb_eArgError, "stream is not writable");
new_file = rb_funcall(rb_cIO, rb_intern("new"), 1, INT2NUM(new_fd));
this->trace_stream = new_file;
PQtrace(this->pgconn, new_fp);
return Qnil;
}
Executes a BEGIN
at the start of the block, and a COMMIT
at the end of the block, or ROLLBACK
if any exception occurs.
# File lib/pg/connection.rb, line 236
def transaction
rollback = false
exec "BEGIN"
yield(self)
rescue Exception
rollback = true
cancel if transaction_status == PG::PQTRANS_ACTIVE
block
exec "ROLLBACK"
raise
ensure
exec "COMMIT" unless rollback
end
returns one of the following statuses:
PQTRANS_IDLE = 0 (connection idle) PQTRANS_ACTIVE = 1 (command in progress) PQTRANS_INTRANS = 2 (idle, within transaction block) PQTRANS_INERROR = 3 (idle, within failed transaction) PQTRANS_UNKNOWN = 4 (cannot determine status)
static VALUE
pgconn_transaction_status(VALUE self)
{
return INT2NUM(PQtransactionStatus(pg_get_pgconn(self)));
}
Obsolete function.
static VALUE
pgconn_tty(VALUE self)
{
return rb_str_new2("");
}
Returns the default TypeMap that is currently set for type casts of query bind parameters.
static VALUE
pgconn_type_map_for_queries_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->type_map_for_queries;
}
Set the default TypeMap that is used for type casts of query bind parameters.
typemap
must be a kind of PG::TypeMap
.
static VALUE
pgconn_type_map_for_queries_set(VALUE self, VALUE typemap)
{
t_pg_connection *this = pg_get_connection( self );
t_typemap *tm;
UNUSED(tm);
/* Check type of method param */
TypedData_Get_Struct(typemap, t_typemap, &pg_typemap_type, tm);
this->type_map_for_queries = typemap;
return typemap;
}
Returns the default TypeMap that is currently set for type casts of result values.
static VALUE
pgconn_type_map_for_results_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->type_map_for_results;
}
Set the default TypeMap that is used for type casts of result values.
typemap
must be a kind of PG::TypeMap
.
static VALUE
pgconn_type_map_for_results_set(VALUE self, VALUE typemap)
{
t_pg_connection *this = pg_get_connection( self );
t_typemap *tm;
UNUSED(tm);
TypedData_Get_Struct(typemap, t_typemap, &pg_typemap_type, tm);
this->type_map_for_results = typemap;
return typemap;
}
Converts an escaped string representation of binary data into binary data — the reverse of escape_bytea
. This is needed when retrieving bytea
data in text format, but not when retrieving it in binary format.
static VALUE
pgconn_s_unescape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t to_len;
VALUE ret;
UNUSED( self );
Check_Type(str, T_STRING);
from = (unsigned char*)StringValueCStr(str);
to = PQunescapeBytea(from, &to_len);
ret = rb_str_new((char*)to, to_len);
PQfreemem(to);
return ret;
}
Disables the message tracing.
static VALUE
pgconn_untrace(VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PQuntrace(this->pgconn);
rb_funcall(this->trace_stream, rb_intern("close"), 0);
this->trace_stream = Qnil;
return Qnil;
}
Returns the authenticated user name.
static VALUE
pgconn_user(VALUE self)
{
char *user = PQuser(pg_get_pgconn(self));
if (!user) return Qnil;
return rb_str_new2(user);
}
Blocks while waiting for notification(s), or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns nil
if timeout is reached, the name of the NOTIFY event otherwise. If used in block form, passes the name of the NOTIFY event
, the generating pid
and the optional payload
string into the block.
static VALUE
pgconn_wait_for_notify(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGnotify *pnotification;
struct timeval timeout;
struct timeval *ptimeout = NULL;
VALUE timeout_in = Qnil, relname = Qnil, be_pid = Qnil, extra = Qnil;
double timeout_sec;
rb_scan_args( argc, argv, "01", &timeout_in );
if ( RTEST(timeout_in) ) {
timeout_sec = NUM2DBL( timeout_in );
timeout.tv_sec = (time_t)timeout_sec;
timeout.tv_usec = (suseconds_t)( (timeout_sec - (long)timeout_sec) * 1e6 );
ptimeout = &timeout;
}
pnotification = (PGnotify*) wait_socket_readable( self, ptimeout, notify_readable);
/* Return nil if the select timed out */
if ( !pnotification ) return Qnil;
relname = rb_str_new2( pnotification->relname );
PG_ENCODING_SET_NOCHECK( relname, this->enc_idx );
be_pid = INT2NUM( pnotification->be_pid );
if ( *pnotification->extra ) {
extra = rb_str_new2( pnotification->extra );
PG_ENCODING_SET_NOCHECK( extra, this->enc_idx );
}
PQfreemem( pnotification );
if ( rb_block_given_p() )
rb_yield_values( 3, relname, be_pid, extra );
return relname;
}