Class: PG::Connection

Inherits:
Object
  • Object
show all
Includes:
Constants
Defined in:
lib/pg/connection.rb,
ext/pg_connection.c

Overview

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.

Constant Summary collapse

CONNECT_ARGUMENT_ORDER =

The order the options are passed to the ::connect method.

%w[host port options tty dbname user password]

Constants included from Constants

PG::Constants::CONNECTION_AUTH_OK, PG::Constants::CONNECTION_AWAITING_RESPONSE, PG::Constants::CONNECTION_BAD, PG::Constants::CONNECTION_MADE, PG::Constants::CONNECTION_NEEDED, PG::Constants::CONNECTION_OK, PG::Constants::CONNECTION_SETENV, PG::Constants::CONNECTION_SSL_STARTUP, PG::Constants::CONNECTION_STARTED, PG::Constants::INVALID_OID, PG::Constants::INV_READ, PG::Constants::INV_WRITE, PG::Constants::InvalidOid, PG::Constants::PGRES_BAD_RESPONSE, PG::Constants::PGRES_COMMAND_OK, PG::Constants::PGRES_COPY_BOTH, PG::Constants::PGRES_COPY_IN, PG::Constants::PGRES_COPY_OUT, PG::Constants::PGRES_EMPTY_QUERY, PG::Constants::PGRES_FATAL_ERROR, PG::Constants::PGRES_NONFATAL_ERROR, PG::Constants::PGRES_POLLING_FAILED, PG::Constants::PGRES_POLLING_OK, PG::Constants::PGRES_POLLING_READING, PG::Constants::PGRES_POLLING_WRITING, PG::Constants::PGRES_SINGLE_TUPLE, PG::Constants::PGRES_TUPLES_OK, PG::Constants::PG_DIAG_COLUMN_NAME, PG::Constants::PG_DIAG_CONSTRAINT_NAME, PG::Constants::PG_DIAG_CONTEXT, PG::Constants::PG_DIAG_DATATYPE_NAME, PG::Constants::PG_DIAG_INTERNAL_POSITION, PG::Constants::PG_DIAG_INTERNAL_QUERY, PG::Constants::PG_DIAG_MESSAGE_DETAIL, PG::Constants::PG_DIAG_MESSAGE_HINT, PG::Constants::PG_DIAG_MESSAGE_PRIMARY, PG::Constants::PG_DIAG_SCHEMA_NAME, PG::Constants::PG_DIAG_SEVERITY, PG::Constants::PG_DIAG_SOURCE_FILE, PG::Constants::PG_DIAG_SOURCE_FUNCTION, PG::Constants::PG_DIAG_SOURCE_LINE, PG::Constants::PG_DIAG_SQLSTATE, PG::Constants::PG_DIAG_STATEMENT_POSITION, PG::Constants::PG_DIAG_TABLE_NAME, PG::Constants::PQERRORS_DEFAULT, PG::Constants::PQERRORS_TERSE, PG::Constants::PQERRORS_VERBOSE, PG::Constants::PQPING_NO_ATTEMPT, PG::Constants::PQPING_NO_RESPONSE, PG::Constants::PQPING_OK, PG::Constants::PQPING_REJECT, PG::Constants::PQTRANS_ACTIVE, PG::Constants::PQTRANS_IDLE, PG::Constants::PQTRANS_INERROR, PG::Constants::PQTRANS_INTRANS, PG::Constants::PQTRANS_UNKNOWN, PG::Constants::SEEK_CUR, PG::Constants::SEEK_END, PG::Constants::SEEK_SET

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Object

call-seq:

PG::Connection.new -> conn
PG::Connection.new(connection_hash) -> conn
PG::Connection.new(connection_string) -> conn
PG::Connection.new(host, port, options, tty, dbname, user, password) ->  conn

Create a connection to the specified server.

host

server hostname

hostaddr

server address (avoids hostname lookup, overrides host)

port

server port number

dbname

connecting database name

user

login user name

password

login password

connect_timeout

maximum time to wait for connection to succeed

options

backend options

tty

(ignored in newer versions of PostgreSQL)

sslmode

(disable|allow|prefer|require)

krbsrvname

kerberos service name

gsslib

GSS library to use for GSSAPI authentication

service

service name to use for additional parameters

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 )

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.



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'ext/pg_connection.c', line 263

static VALUE
pgconn_init(int argc, VALUE *argv, VALUE self)
{
	t_pg_connection *this;
	VALUE conninfo;
	VALUE error;

	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 structure");

	if (PQstatus(this->pgconn) == CONNECTION_BAD) {
		error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(this->pgconn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}

	pgconn_set_default_encoding( self );

	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, self, pgconn_finish, self);
	}
	return self;
}

Class Method Details

.conndefaultsObject

call-seq:

PG::Connection.conndefaults() -> Array

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



394
395
396
397
398
399
400
401
402
403
404
405
# File 'ext/pg_connection.c', line 394

static VALUE
pgconn_s_conndefaults(VALUE self)
{
	PQconninfoOption *options = PQconndefaults();
	VALUE array = pgconn_make_conninfo_array( options );

	PQconninfoFree(options);

	UNUSED( self );

	return array;
}

.conndefaults_hashObject

Return the Postgres connection defaults structure as a Hash keyed by option keyword (as a Symbol).

See also #conndefaults



227
228
229
230
231
# File 'lib/pg/connection.rb', line 227

def self.conndefaults_hash
	return self.conndefaults.each_with_object({}) do |info, hash|
		hash[ info[:keyword].to_sym ] = info[:val]
	end
end

.PG::Connection.connect_start(connection_hash) ⇒ Object .PG::Connection.connect_start(connection_string) ⇒ Object .PG::Connection.connect_start(host, port, options, tty, dbname, login, password) ⇒ Object

This is an asynchronous version of PG::Connection.connect().

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, or include the ‘options’ connection parameter.



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'ext/pg_connection.c', line 307

static VALUE
pgconn_s_connect_start( int argc, VALUE *argv, VALUE klass )
{
	VALUE rb_conn;
	VALUE conninfo;
	VALUE error;
	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 structure");

	if ( PQstatus(this->pgconn) == CONNECTION_BAD ) {
		error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(this->pgconn));
		rb_iv_set(error, "@connection", rb_conn);
		rb_exc_raise(error);
	}

	if ( rb_block_given_p() ) {
		return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn );
	}
	return rb_conn;
}

.PG::Connection.encrypt_password(password, username) ⇒ String

This is an older, deprecated version of #encrypt_password. The difference is that this function always uses md5 as the encryption algorithm.

Returns:

  • (String)


468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'ext/pg_connection.c', line 468

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 );

	OBJ_INFECT( rval, password );
	OBJ_INFECT( rval, username );

	return rval;
}

.escape_bytea(string) ⇒ 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.

Returns:

  • (String)


1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
# File 'ext/pg_connection.c', line 1628

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);
	OBJ_INFECT(ret, str);
	PQfreemem(to);
	return ret;
}

.escape_string(str) ⇒ String

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.

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.

Returns:

  • (String)


1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
# File 'ext/pg_connection.c', line 1573

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);

	Check_Type(string, T_STRING);
	enc_idx = ENCODING_GET( singleton ? string : self );
	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) {
			rb_raise(rb_ePGerror, "%s", PQerrorMessage(pg_get_pgconn(self)));
		}
	} else {
		size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
	}
	rb_str_set_len(result, size);
	OBJ_INFECT(result, string);

	return result;
}

.parse_connect_args(*args) ⇒ Object

Parse the connection args into a connection-parameter string. See PG::Connection.new for valid arguments.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/pg/connection.rb', line 35

def self::parse_connect_args( *args )
	return '' if args.empty?

	hash_arg = args.last.is_a?( Hash ) ? args.pop : {}
	option_string = ''
	options = {}

	# Parameter 'fallback_application_name' was introduced in PostgreSQL 9.0
	# together with PQescapeLiteral().
	if PG::Connection.instance_methods.find {|m| m.to_sym == :escape_literal }
		options[:fallback_application_name] = $0.sub( /^(.{30}).{4,}(.{30})$/ ){ $1+"..."+$2 }
	end

	if args.length == 1
		case args.first
		when URI, /\A#{URI.regexp}\z/
			uri = URI(args.first)
			options.merge!( Hash[URI.decode_www_form( uri.query )] ) if uri.query
		when /=/
			# Option string style
			option_string = args.first.to_s
		else
			# Positional parameters
			options[CONNECT_ARGUMENT_ORDER.first.to_sym] = args.first
		end
	else
		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)|
			options[ k.to_sym ] = v if v
		end
	end

	options.merge!( hash_arg )

	if uri
		uri.host     = nil if options[:host]
		uri.port     = nil if options[:port]
		uri.user     = nil if options[:user]
		uri.password = nil if options[:password]
		uri.path     = '' if options[:dbname]
		uri.query    = URI.encode_www_form( options )
		return uri.to_s.sub( /^#{uri.scheme}:(?!\/\/)/, "#{uri.scheme}://" )
	else
		option_string += ' ' unless option_string.empty? && options.empty?
		return option_string + options.map { |k,v| "#{k}=#{quote_connstr(v)}" }.join( ' ' )
	end
end

.PG::Connection.ping(connection_hash) ⇒ Integer .PG::Connection.ping(connection_string) ⇒ Integer .PG::Connection.ping(host, port, options, tty, dbname, login, password) ⇒ Integer

Check server status.

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)

Available since PostgreSQL-9.1

Overloads:

  • .PG::Connection.ping(connection_hash) ⇒ Integer

    Returns:

    • (Integer)
  • .PG::Connection.ping(connection_string) ⇒ Integer

    Returns:

    • (Integer)
  • .PG::Connection.ping(host, port, options, tty, dbname, login, password) ⇒ Integer

    Returns:

    • (Integer)


359
360
361
362
363
364
365
366
367
368
369
# File 'ext/pg_connection.c', line 359

static VALUE
pgconn_s_ping( int argc, VALUE *argv, VALUE klass )
{
	PGPing ping;
	VALUE conninfo;

	conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
	ping     = PQping( StringValueCStr(conninfo) );

	return INT2FIX((int)ping);
}

.quote_connstr(value) ⇒ Object

Quote the given value for use in a connection-parameter string.



28
29
30
# File 'lib/pg/connection.rb', line 28

def self::quote_connstr( value )
	return "'" + value.to_s.gsub( /[\\']/ ) {|m| '\\' + m } + "'"
end

.quote_ident(str) ⇒ String .quote_ident(array) ⇒ String .PG::Connection.quote_ident(str) ⇒ String .PG::Connection.quote_ident(array) ⇒ String

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.

Overloads:

  • .quote_ident(str) ⇒ String

    Returns:

    • (String)
  • .quote_ident(array) ⇒ String

    Returns:

    • (String)
  • .PG::Connection.quote_ident(str) ⇒ String

    Returns:

    • (String)
  • .PG::Connection.quote_ident(array) ⇒ String

    Returns:

    • (String)


3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
# File 'ext/pg_connection.c', line 3032

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 = ENCODING_GET( self );
	}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);

	OBJ_INFECT(ret, str_or_array);

	return ret;
}

.PG::Connection.unescape_bytea(string) ⇒ Object

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.



1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
# File 'ext/pg_connection.c', line 1661

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);
	OBJ_INFECT(ret, str);
	PQfreemem(to);
	return ret;
}

Instance Method Details

#async_exec(sql[, params, result_format ]) ⇒ PG::Result #async_exec(sql[, params, result_format ]) {|pg_result| ... } ⇒ Object Also known as: async_query

This function has the same behavior as #exec, but is implemented using the asynchronous command processing API of libpq.

Overloads:

  • #async_exec(sql[, params, result_format ]) ⇒ PG::Result

    Returns:

  • #async_exec(sql[, params, result_format ]) {|pg_result| ... } ⇒ Object

    Yields:

    • (pg_result)


3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
# File 'ext/pg_connection.c', line 3152

static VALUE
pgconn_async_exec(int argc, VALUE *argv, VALUE self)
{
	VALUE rb_pgresult = Qnil;

	/* remove any remaining results from the queue */
	pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */
	pgconn_get_last_result( self );

	pgconn_send_query( argc, argv, self );
	pgconn_block( 0, NULL, self );
	rb_pgresult = pgconn_get_last_result( self );

	if ( rb_block_given_p() ) {
		return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
	}
	return rb_pgresult;
}

#backend_pidInteger

Returns the process ID of the backend server process for this connection. Note that this is a PID on database server host.

Returns:

  • (Integer)


921
922
923
924
925
# File 'ext/pg_connection.c', line 921

static VALUE
pgconn_backend_pid(VALUE self)
{
	return INT2NUM(PQbackendPID(pg_get_pgconn(self)));
}

#block([ timeout ]) ⇒ Boolean

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.

Returns:

  • (Boolean)


3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
# File 'ext/pg_connection.c', line 3071

static VALUE
pgconn_block( int argc, VALUE *argv, VALUE self ) {
	PGconn *conn = pg_get_pgconn( self );

	/* If WIN32 and Ruby 1.9 do not use rb_thread_select() which sometimes hangs
	 * and does not wait (nor sleep) any time even if timeout is given.
	 * Instead use the Winsock events and rb_w32_wait_events(). */

	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( conn, ptimeout, get_result_readable);

	if( !ret )
		return Qfalse;

	return Qtrue;
}

#cancelString

Requests cancellation of the command currently being processed. (Only implemented in PostgreSQL >= 8.0)

Returns nil on success, or a string containing the error message if a failure occurs.

Returns:

  • (String)


2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
# File 'ext/pg_connection.c', line 2234

static VALUE
pgconn_cancel(VALUE self)
{
	char errbuf[256];
	PGcancel *cancel;
	VALUE retval;
	int ret;

	cancel = PQgetCancel(pg_get_pgconn(self));
	if(cancel == NULL)
		rb_raise(rb_ePGerror,"Invalid connection!");

	ret = gvl_PQcancel(cancel, errbuf, 256);
	if(ret == 1)
		retval = Qnil;
	else
		retval = rb_str_new2(errbuf);

	PQfreeCancel(cancel);
	return retval;
}

#conndefaultsObject

Returns an array of Hashes with connection defaults. See ::conndefaults for details.



219
220
221
# File 'lib/pg/connection.rb', line 219

def conndefaults
	return self.class.conndefaults
end

#conndefaults_hashObject

Returns a Hash with connection defaults. See ::conndefaults_hash for details.



235
236
237
# File 'lib/pg/connection.rb', line 235

def conndefaults_hash
	return self.class.conndefaults_hash
end

#connect_pollInteger

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:

conn = PG::Connection.connect_start("dbname=mydatabase")
socket = conn.socket_io
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)
    if(not select([socket], [], [], 10.0))
      raise "Asynchronous connection timed out!"
    end
  elsif(status == PG::PGRES_POLLING_WRITING)
    if(not select([], [socket], [], 10.0))
      raise "Asynchronous connection timed out!"
    end
  end
  status = conn.connect_poll
end
# now conn.status == CONNECTION_OK, and connection
# is ready.

Returns:

  • (Integer)


528
529
530
531
532
533
534
# File 'ext/pg_connection.c', line 528

static VALUE
pgconn_connect_poll(VALUE self)
{
	PostgresPollingStatusType status;
	status = gvl_PQconnectPoll(pg_get_pgconn(self));
	return INT2FIX((int)status);
}

#connection_needs_passwordBoolean

Returns true if the authentication method required a password, but none was available. false otherwise.

Returns:

  • (Boolean)


934
935
936
937
938
# File 'ext/pg_connection.c', line 934

static VALUE
pgconn_connection_needs_password(VALUE self)
{
	return PQconnectionNeedsPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}

#connection_used_passwordBoolean

Returns true if the authentication method used a caller-supplied password, false otherwise.

Returns:

  • (Boolean)


947
948
949
950
951
# File 'ext/pg_connection.c', line 947

static VALUE
pgconn_connection_used_password(VALUE self)
{
	return PQconnectionUsedPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}

#conninfoHash

Returns the connection options used by a live connection.

Available since PostgreSQL-9.3

Returns:

  • (Hash)


727
728
729
730
731
732
733
734
735
736
737
# File 'ext/pg_connection.c', line 727

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;
}

#conninfo_hashObject

Return the Postgres connection info structure as a Hash keyed by option keyword (as a Symbol).

See also #conninfo



246
247
248
249
250
# File 'lib/pg/connection.rb', line 246

def conninfo_hash
	return self.conninfo.each_with_object({}) do |info, hash|
		hash[ info[:keyword].to_sym ] = info[:val]
	end
end

#consume_inputObject

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.



2116
2117
2118
# File 'ext/pg_connection.c', line 2116

static VALUE
pgconn_consume_input(self)
VALUE self;

#copy_data(sql, coder = nil) ⇒ Object

call-seq:

conn.copy_data( sql [, coder] ) {|sql_result| ... } -> PG::Result

Execute a copy process for transfering 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"]


155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/pg/connection.rb', line 155

def copy_data( sql, coder=nil )
	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
			while get_copy_data
			end
			while get_result
			end
			raise
		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, "Not all COPY data retrieved"
			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

#dbObject

Returns the connected database name.



626
627
628
629
630
631
632
# File 'ext/pg_connection.c', line 626

static VALUE
pgconn_db(VALUE self)
{
	char *db = PQdb(pg_get_pgconn(self));
	if (!db) return Qnil;
	return rb_tainted_str_new2(db);
}

#decoder_for_get_copy_dataPG::Coder

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.

Returns:



3874
3875
3876
3877
3878
3879
3880
# File 'ext/pg_connection.c', line 3874

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;
}

#decoder_for_get_copy_data=(decoder) ⇒ Object

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.



3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
# File 'ext/pg_connection.c', line 3845

static VALUE
pgconn_decoder_for_get_copy_data_set(VALUE self, VALUE typemap)
{
	t_pg_connection *this = pg_get_connection( self );

	if( typemap != Qnil ){
		if ( !rb_obj_is_kind_of(typemap, rb_cPG_Coder) ) {
			rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::Coder)",
					rb_obj_classname( typemap ) );
		}
		Check_Type(typemap, T_DATA);
	}
	this->decoder_for_get_copy_data = typemap;

	return typemap;
}

#describe_portal(portal_name) ⇒ PG::Result

Retrieve information about the portal portal_name.

Returns:



1504
1505
1506
# File 'ext/pg_connection.c', line 1504

static VALUE
pgconn_describe_portal(self, stmt_name)
VALUE self, stmt_name;

#describe_prepared(statement_name) ⇒ PG::Result

Retrieve information about the prepared statement statement_name.

Returns:



1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# File 'ext/pg_connection.c', line 1478

static VALUE
pgconn_describe_prepared(VALUE self, VALUE stmt_name)
{
	PGresult *result;
	VALUE rb_pgresult;
	PGconn *conn = pg_get_pgconn(self);
	const char *stmt;
	if(NIL_P(stmt_name)) {
		stmt = NULL;
	}
	else {
		stmt = pg_cstr_enc(stmt_name, ENCODING_GET(self));
	}
	result = gvl_PQdescribePrepared(conn, stmt);
	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);
	return rb_pgresult;
}

#encoder_for_put_copy_dataPG::Coder

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.

Returns:



3825
3826
3827
3828
3829
3830
3831
# File 'ext/pg_connection.c', line 3825

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;
}

#encoder_for_put_copy_data=(encoder) ⇒ Object

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.



3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
# File 'ext/pg_connection.c', line 3796

static VALUE
pgconn_encoder_for_put_copy_data_set(VALUE self, VALUE typemap)
{
	t_pg_connection *this = pg_get_connection( self );

	if( typemap != Qnil ){
		if ( !rb_obj_is_kind_of(typemap, rb_cPG_Coder) ) {
			rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::Coder)",
					rb_obj_classname( typemap ) );
		}
		Check_Type(typemap, T_DATA);
	}
	this->encoder_for_put_copy_data = typemap;

	return typemap;
}

#encrypt_password(password, username, algorithm = nil) ⇒ String

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

Returns:

  • (String)


430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# File 'ext/pg_connection.c', line 430

static VALUE
pgconn_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 );

		OBJ_INFECT( rval, password );
		OBJ_INFECT( rval, username );
		OBJ_INFECT( rval, algorithm );
	} else {
		rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
	}

	return rval;
}

#error_messageString

Returns the error message about connection.

Returns:

  • (String)


835
836
837
838
839
840
841
# File 'ext/pg_connection.c', line 835

static VALUE
pgconn_error_message(VALUE self)
{
	char *error = PQerrorMessage(pg_get_pgconn(self));
	if (!error) return Qnil;
	return rb_tainted_str_new2(error);
}

#escape_bytea(string) ⇒ 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.

Returns:

  • (String)


1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
# File 'ext/pg_connection.c', line 1628

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);
	OBJ_INFECT(ret, str);
	PQfreemem(to);
	return ret;
}

#escape_identifier(str) ⇒ String

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.

Available since PostgreSQL-9.0

Returns:

  • (String)


1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
# File 'ext/pg_connection.c', line 1731

static VALUE
pgconn_escape_identifier(VALUE self, VALUE string)
{
	PGconn *conn = pg_get_pgconn(self);
	char *escaped = NULL;
	VALUE error;
	VALUE result = Qnil;
	int enc_idx = ENCODING_GET(self);

	Check_Type(string, T_STRING);
	if( ENCODING_GET(string) != enc_idx ){
		string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
	}

	escaped = PQescapeIdentifier(conn, RSTRING_PTR(string), RSTRING_LEN(string));
	if (escaped == NULL)
	{
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
		return Qnil;
	}
	result = rb_str_new2(escaped);
	PQfreemem(escaped);
	OBJ_INFECT(result, string);
	PG_ENCODING_SET_NOCHECK(result, enc_idx);

	return result;
}

#escape_literal(str) ⇒ String

Escape an arbitrary String str as a literal.

Available since PostgreSQL-9.0

Returns:

  • (String)


1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
# File 'ext/pg_connection.c', line 1689

static VALUE
pgconn_escape_literal(VALUE self, VALUE string)
{
	PGconn *conn = pg_get_pgconn(self);
	char *escaped = NULL;
	VALUE error;
	VALUE result = Qnil;
	int enc_idx = ENCODING_GET(self);

	Check_Type(string, T_STRING);
	if( ENCODING_GET(string) != enc_idx ){
		string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
	}

	escaped = PQescapeLiteral(conn, RSTRING_PTR(string), RSTRING_LEN(string));
	if (escaped == NULL)
	{
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
		return Qnil;
	}
	result = rb_str_new2(escaped);
	PQfreemem(escaped);
	OBJ_INFECT(result, string);
	PG_ENCODING_SET_NOCHECK(result, enc_idx);

	return result;
}

#escape_string(str) ⇒ String Also known as: escape

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.

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.

Returns:

  • (String)


1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
# File 'ext/pg_connection.c', line 1573

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);

	Check_Type(string, T_STRING);
	enc_idx = ENCODING_GET( singleton ? string : self );
	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) {
			rb_raise(rb_ePGerror, "%s", PQerrorMessage(pg_get_pgconn(self)));
		}
	} else {
		size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
	}
	rb_str_set_len(result, size);
	OBJ_INFECT(result, string);

	return result;
}

#exec(sql) ⇒ PG::Result #exec(sql) {|pg_result| ... } ⇒ Object Also known as: query

Sends SQL query request specified by sql to PostgreSQL. Returns a PG::Result instance on success. 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 implemented on the synchronous command processing API of libpq, whereas #async_exec is implemented on the asynchronous API. #exec is somewhat faster that #async_exec, but blocks any signals to be processed until the query is finished. This is most notably visible by a delayed reaction to Control+C. Both methods ensure that other threads can process while waiting for the server to complete the request.

Overloads:

  • #exec(sql) ⇒ PG::Result

    Returns:

  • #exec(sql) {|pg_result| ... } ⇒ Object

    Yields:

    • (pg_result)


983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'ext/pg_connection.c', line 983

static VALUE
pgconn_exec(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;

	/* If called with no parameters, use PQexec */
	if ( argc == 1 ) {
		VALUE query_str = argv[0];

		result = gvl_PQexec(conn, pg_cstr_enc(query_str, ENCODING_GET(self)));
		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;
	}

	/* Otherwise, just call #exec_params instead for backward-compatibility */
	else {
		return pgconn_exec_params( argc, argv, self );
	}

}

#exec_params(sql, params[, result_format[, type_map]]) ⇒ PG::Result #exec_params(sql, params[, result_format[, type_map]]) {|pg_result| ... } ⇒ Object

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, $1, $2, 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.

Overloads:

  • #exec_params(sql, params[, result_format[, type_map]]) ⇒ PG::Result

    Returns:

  • #exec_params(sql, params[, result_format[, type_map]]) {|pg_result| ... } ⇒ Object

    Yields:

    • (pg_result)


1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
# File 'ext/pg_connection.c', line 1298

static VALUE
pgconn_exec_params( int argc, VALUE *argv, VALUE self )
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;
	VALUE command, in_res_fmt;
	int nParams;
	int resultFormat;
	struct query_params_data paramsData = { ENCODING_GET(self) };

	rb_scan_args(argc, argv, "13", &command, &paramsData.params, &in_res_fmt, &paramsData.typemap);
	paramsData.with_types = 1;

	/*
	 * Handle the edge-case where the caller is coming from #exec, but passed an explict +nil+
	 * for the second parameter.
	 */
	if ( NIL_P(paramsData.params) ) {
		return pgconn_exec( 1, argv, self );
	}
	pgconn_query_assign_typemap( self, &paramsData );

	resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
	nParams = alloc_query_params( &paramsData );

	result = gvl_PQexecParams(conn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
		(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);

	free_query_params( &paramsData );

	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;
}

#exec_prepared(statement_name[, params, result_format[, type_map]]) ⇒ PG::Result #exec_prepared(statement_name[, params, result_format[, type_map]]) {|pg_result| ... } ⇒ Object

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, $1, $2, 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.

Overloads:

  • #exec_prepared(statement_name[, params, result_format[, type_map]]) ⇒ PG::Result

    Returns:

  • #exec_prepared(statement_name[, params, result_format[, type_map]]) {|pg_result| ... } ⇒ Object

    Yields:

    • (pg_result)


1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
# File 'ext/pg_connection.c', line 1434

static VALUE
pgconn_exec_prepared(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;
	VALUE name, in_res_fmt;
	int nParams;
	int resultFormat;
	struct query_params_data paramsData = { ENCODING_GET(self) };

	rb_scan_args(argc, argv, "13", &name, &paramsData.params, &in_res_fmt, &paramsData.typemap);
	paramsData.with_types = 0;

	if(NIL_P(paramsData.params)) {
		paramsData.params = rb_ary_new2(0);
	}
	pgconn_query_assign_typemap( self, &paramsData );

	resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
	nParams = alloc_query_params( &paramsData );

	result = gvl_PQexecPrepared(conn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
		(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
		resultFormat);

	free_query_params( &paramsData );

	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;
}

#external_encodingEncoding

Return the server_encoding of the connected database as a Ruby Encoding object. The SQL_ASCII encoding is mapped to to ASCII_8BIT.

Returns:

  • (Encoding)


3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
# File 'ext/pg_connection.c', line 3628

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;

	/* Use cached value if found */
	if ( RTEST(this->external_encoding) ) return this->external_encoding;

	pg_encname = PQparameterStatus( this->pgconn, "server_encoding" );
	enc = pg_get_pg_encname_as_rb_encoding( pg_encname );
	this->external_encoding = rb_enc_from_encoding( enc );

	return this->external_encoding;
}

#finishObject Also known as: close

Closes the backend connection.



542
543
544
545
546
547
548
549
550
551
# File 'ext/pg_connection.c', line 542

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;
}

#finished?Boolean

Returns true if the backend connection has been closed.

Returns:

  • (Boolean)


560
561
562
563
564
565
566
# File 'ext/pg_connection.c', line 560

static VALUE
pgconn_finished_p( VALUE self )
{
	t_pg_connection *this = pg_get_connection( self );
	if ( this->pgconn ) return Qfalse;
	return Qtrue;
}

#flushBoolean

Attempts to flush any queued output data to the server. Returns true if data is successfully flushed, false if not (can only return false if connection is nonblocking. Raises PG::Error if some other failure occurred.

Returns:

  • (Boolean)


2208
2209
2210
# File 'ext/pg_connection.c', line 2208

static VALUE
pgconn_flush(self)
VALUE self;

#get_client_encodingString

Returns the client encoding as a String.

Returns:

  • (String)


2923
2924
2925
2926
2927
2928
# File 'ext/pg_connection.c', line 2923

static VALUE
pgconn_get_client_encoding(VALUE self)
{
	char *encoding = (char *)pg_encoding_to_char(PQclientEncoding(pg_get_pgconn(self)));
	return rb_tainted_str_new2(encoding);
}

#get_copy_data([ async = false [, decoder = nil ]]) ⇒ String

Return a string containing one row of data, nil if the copy is done, or false if the call would block (only possible if async is true).

decoder can be a PG::Coder derivation (typically PG::TextDecoder::CopyRow). This decodes the received data fields from PostgreSQL’s COPY text format to an Array of Strings. Optionally the decoder can type cast the fields to various Ruby types in one step, if PG::TextDecoder::CopyRow#type_map is set accordingly.

See also #copy_data.

Returns:

  • (String)


2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
# File 'ext/pg_connection.c', line 2650

static VALUE
pgconn_get_copy_data(int argc, VALUE *argv, VALUE self )
{
	VALUE async_in;
	VALUE error;
	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 = DATA_PTR( this->decoder_for_get_copy_data );
		}
	} else if( rb_obj_is_kind_of(decoder, rb_cPG_Coder) ) {
		Data_Get_Struct( decoder, t_pg_coder, p_coder );
	} else {
		rb_raise( rb_eTypeError, "wrong decoder type %s (expected some kind of PG::Coder)",
				rb_obj_classname( decoder ) );
	}

	ret = gvl_PQgetCopyData(this->pgconn, &buffer, RTEST(async_in));
	if(ret == -2) { /* error */
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(this->pgconn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	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, ENCODING_GET(self) );
	} else {
		result = rb_tainted_str_new(buffer, ret);
	}

	PQfreemem(buffer);
	return result;
}

#get_last_resultPG::Result

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.

This function is similar to #get_result except that it is designed to get one and only one result.

Returns:



3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
# File 'ext/pg_connection.c', line 3115

static VALUE
pgconn_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)
			break;
	}

	if (prev) {
		rb_pgresult = pg_new_result( prev, self );
		pg_result_check(rb_pgresult);
	}

	return rb_pgresult;
}

#get_resultPG::Result #get_result {|pg_result| ... } ⇒ Object

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.

Overloads:

  • #get_resultPG::Result

    Returns:

  • #get_result {|pg_result| ... } ⇒ Object

    Yields:

    • (pg_result)


2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
# File 'ext/pg_connection.c', line 2090

static VALUE
pgconn_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;
}

#hostObject

Returns the connected server name.



668
669
670
671
672
673
674
# File 'ext/pg_connection.c', line 668

static VALUE
pgconn_host(VALUE self)
{
	char *host = PQhost(pg_get_pgconn(self));
	if (!host) return Qnil;
	return rb_tainted_str_new2(host);
}

#internal_encodingEncoding

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’

Returns:

  • (Encoding)


3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
# File 'ext/pg_connection.c', line 3561

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;
	}
}

#internal_encoding=(value) ⇒ Object

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.



3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
# File 'ext/pg_connection.c', line 3588

static VALUE
pgconn_internal_encoding_set(VALUE self, VALUE enc)
{
	VALUE enc_inspect;
	if (NIL_P(enc)) {
		pgconn_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_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;
	}

	enc_inspect = rb_inspect(enc);
	rb_raise( rb_ePGerror, "unknown encoding: %s", StringValueCStr(enc_inspect) );

	return Qnil;
}

#is_busyBoolean

Returns true if a command is busy, that is, if PQgetResult would block. Otherwise returns false.

Returns:

  • (Boolean)


2138
2139
2140
# File 'ext/pg_connection.c', line 2138

static VALUE
pgconn_is_busy(self)
VALUE self;

#isnonblockingBoolean Also known as: nonblocking?

Returns true if a command is busy, that is, if PQgetResult would block. Otherwise returns false.

Returns:

  • (Boolean)


2191
2192
2193
# File 'ext/pg_connection.c', line 2191

static VALUE
pgconn_isnonblocking(self)
VALUE self;

#lo_close(lo_desc) ⇒ nil Also known as: loclose

Closes the postgres large object of lo_desc.

Returns:

  • (nil)


3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
# File 'ext/pg_connection.c', line 3512

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)
		rb_raise(rb_ePGerror,"lo_close failed");

	return Qnil;
}

#lo_creat([mode]) ⇒ Integer Also known as: locreat

Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PG::Error.

Returns:

  • (Integer)


3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
# File 'ext/pg_connection.c', line 3262

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)
		rb_raise(rb_ePGerror, "lo_creat failed");

	return UINT2NUM(lo_oid);
}

#lo_create(oid) ⇒ Integer Also known as: locreate

Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PG::Error.

Returns:

  • (Integer)


3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
# File 'ext/pg_connection.c', line 3289

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)
		rb_raise(rb_ePGerror, "lo_create failed");

	return UINT2NUM(ret);
}

#lo_export(oid, file) ⇒ nil Also known as: loexport

Saves a large object of oid to a file.

Returns:

  • (nil)


3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
# File 'ext/pg_connection.c', line 3333

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) {
		rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
	}
	return Qnil;
}

#lo_import(file) ⇒ Integer Also known as: loimport

Import a file to a large object. Returns a large object Oid.

On failure, it raises a PG::Error.

Returns:

  • (Integer)


3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
# File 'ext/pg_connection.c', line 3311

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) {
		rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
	}
	return UINT2NUM(lo_oid);
}

#lo_lseek(lo_desc, offset, whence) ⇒ Integer Also known as: lolseek, lo_seek, loseek

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:

  • (Integer)


3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
# File 'ext/pg_connection.c', line 3454

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) {
		rb_raise(rb_ePGerror, "lo_lseek failed");
	}

	return INT2FIX(ret);
}

#lo_open(oid, [mode]) ⇒ Integer Also known as: loopen

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.

Returns:

  • (Integer)


3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
# File 'ext/pg_connection.c', line 3358

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) {
		rb_raise(rb_ePGerror, "can't open large object: %s", PQerrorMessage(conn));
	}
	return INT2FIX(fd);
}

#lo_read(lo_desc, len) ⇒ String Also known as: loread

Attempts to read len bytes from large object lo_desc, returns resulting data.

Returns:

  • (String)


3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
# File 'ext/pg_connection.c', line 3413

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;

  buffer = ALLOC_N(char, len);
	if(buffer == NULL)
		rb_raise(rb_eNoMemError, "ALLOC failed!");

	if (len < 0){
		rb_raise(rb_ePGerror,"nagative length %d given", len);
	}

	if((ret = lo_read(conn, lo_desc, buffer, len)) < 0)
		rb_raise(rb_ePGerror, "lo_read failed");

	if(ret == 0) {
		xfree(buffer);
		return Qnil;
	}

	str = rb_tainted_str_new(buffer, ret);
	xfree(buffer);

	return str;
}

#lo_tell(lo_desc) ⇒ Integer Also known as: lotell

Returns the current position of the large object lo_desc.

Returns:

  • (Integer)


3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
# File 'ext/pg_connection.c', line 3474

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)
		rb_raise(rb_ePGerror,"lo_tell failed");

	return INT2FIX(position);
}

#lo_truncate(lo_desc, len) ⇒ nil Also known as: lotruncate

Truncates the large object lo_desc to size len.

Returns:

  • (nil)


3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
# File 'ext/pg_connection.c', line 3493

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)
		rb_raise(rb_ePGerror,"lo_truncate failed");

	return Qnil;
}

Unlinks (deletes) the postgres large object of oid.

Returns:

  • (nil)


3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
# File 'ext/pg_connection.c', line 3530

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)
		rb_raise(rb_ePGerror,"lo_unlink failed");

	return Qnil;
}

#lo_write(lo_desc, buffer) ⇒ Integer Also known as: lowrite

Writes the string buffer to the large object lo_desc. Returns the number of bytes written.

Returns:

  • (Integer)


3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
# File 'ext/pg_connection.c', line 3386

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) {
		rb_raise(rb_ePGerror, "write buffer zero string");
	}
	if((n = lo_write(conn, fd, StringValuePtr(buffer),
				RSTRING_LEN(buffer))) < 0) {
		rb_raise(rb_ePGerror, "lo_write failed: %s", PQerrorMessage(conn));
	}

	return INT2FIX(n);
}

#make_empty_pgresult(status) ⇒ PG::Result

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

Returns:



1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
# File 'ext/pg_connection.c', line 1541

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;
}

#notifiesObject

Returns a hash of the unprocessed notifications. If there is no unprocessed notifier, it returns nil.



2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
# File 'ext/pg_connection.c', line 2264

static VALUE
pgconn_notifies(VALUE self)
{
	PGconn* conn = pg_get_pgconn(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(conn);
	if (notification == NULL) {
		return Qnil;
	}

	hash = rb_hash_new();
	relname = rb_tainted_str_new2(notification->relname);
	be_pid = INT2NUM(notification->be_pid);
	extra = rb_tainted_str_new2(notification->extra);
	PG_ENCODING_SET_NOCHECK( relname, ENCODING_GET(self) );
	PG_ENCODING_SET_NOCHECK( extra, ENCODING_GET(self) );

	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;
}

#optionsObject

Returns backend option string.



709
710
711
712
713
714
715
# File 'ext/pg_connection.c', line 709

static VALUE
pgconn_options(VALUE self)
{
	char *options = PQoptions(pg_get_pgconn(self));
	if (!options) return Qnil;
	return rb_tainted_str_new2(options);
}

#parameter_status(param_name) ⇒ String

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.

Returns:

  • (String)


788
789
790
791
792
793
794
795
796
# File 'ext/pg_connection.c', line 788

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_tainted_str_new2(ret);
}

#passObject

Returns the authenticated password.



654
655
656
657
658
659
660
# File 'ext/pg_connection.c', line 654

static VALUE
pgconn_pass(VALUE self)
{
	char *user = PQpass(pg_get_pgconn(self));
	if (!user) return Qnil;
	return rb_tainted_str_new2(user);
}

#portObject

Returns the connected server port number.



682
683
684
685
686
687
# File 'ext/pg_connection.c', line 682

static VALUE
pgconn_port(VALUE self)
{
	char* port = PQport(pg_get_pgconn(self));
	return INT2NUM(atol(port));
}

#prepare(stmt_name, sql[, param_types ]) ⇒ PG::Result

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, $1, $2, etc., inside the SQL query.

Returns:



1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
# File 'ext/pg_connection.c', line 1359

static VALUE
pgconn_prepare(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(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 = ENCODING_GET(self);

	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(conn, name_cstr, command_cstr, nParams, paramTypes);

	xfree(paramTypes);

	rb_pgresult = pg_new_result(result, self);
	pg_result_check(rb_pgresult);
	return rb_pgresult;
}

#protocol_versionInteger

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.)

Returns:

  • (Integer)


806
807
808
809
810
# File 'ext/pg_connection.c', line 806

static VALUE
pgconn_protocol_version(VALUE self)
{
	return INT2NUM(PQprotocolVersion(pg_get_pgconn(self)));
}

#put_copy_data(buffer[, encoder]) ⇒ Boolean

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.

Returns:

  • (Boolean)


2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
# File 'ext/pg_connection.c', line 2538

static VALUE
pgconn_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 = DATA_PTR( this->encoder_for_put_copy_data );
		}
	} else if( rb_obj_is_kind_of(encoder, rb_cPG_Coder) ) {
		Data_Get_Struct( encoder, t_pg_coder, p_coder );
	} else {
		rb_raise( rb_eTypeError, "wrong encoder type %s (expected some kind of PG::Coder)",
				rb_obj_classname( encoder ) );
	}

	if( p_coder ){
		t_pg_coder_enc_func enc_func;
		int enc_idx = ENCODING_GET(self);

		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) {
		VALUE error = rb_exc_new2(rb_ePGerror, PQerrorMessage(this->pgconn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	RB_GC_GUARD(intermediate);
	RB_GC_GUARD(buffer);

	return (ret) ? Qtrue : Qfalse;
}

#put_copy_end([ error_message ]) ⇒ Boolean

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).

Returns:

  • (Boolean)


2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
# File 'ext/pg_connection.c', line 2610

static VALUE
pgconn_put_copy_end(int argc, VALUE *argv, VALUE self)
{
	VALUE str;
	VALUE error;
	int ret;
	const char *error_message = NULL;
	PGconn *conn = pg_get_pgconn(self);

	if (rb_scan_args(argc, argv, "01", &str) == 0)
		error_message = NULL;
	else
		error_message = pg_cstr_enc(str, ENCODING_GET(self));

	ret = gvl_PQputCopyEnd(conn, error_message);
	if(ret == -1) {
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return (ret) ? Qtrue : Qfalse;
}

#quote_ident(str) ⇒ String #quote_ident(array) ⇒ String #PG::Connection.quote_ident(str) ⇒ String #PG::Connection.quote_ident(array) ⇒ String

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.

Overloads:

  • #quote_ident(str) ⇒ String

    Returns:

    • (String)
  • #quote_ident(array) ⇒ String

    Returns:

    • (String)
  • #PG::Connection.quote_ident(str) ⇒ String

    Returns:

    • (String)
  • #PG::Connection.quote_ident(array) ⇒ String

    Returns:

    • (String)


3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
# File 'ext/pg_connection.c', line 3032

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 = ENCODING_GET( self );
	}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);

	OBJ_INFECT(ret, str_or_array);

	return ret;
}

#resetObject

Resets the backend connection. This method closes the backend connection and tries to re-connect.



576
577
578
579
580
581
582
# File 'ext/pg_connection.c', line 576

static VALUE
pgconn_reset( VALUE self )
{
	pgconn_close_socket_io( self );
	gvl_PQreset( pg_get_pgconn(self) );
	return self;
}

#reset_pollInteger

Checks the status of a connection reset operation. See #connect_start and #connect_poll for usage information and return values.

Returns:

  • (Integer)


611
612
613
614
615
616
617
# File 'ext/pg_connection.c', line 611

static VALUE
pgconn_reset_poll(VALUE self)
{
	PostgresPollingStatusType status;
	status = gvl_PQresetPoll(pg_get_pgconn(self));
	return INT2FIX((int)status);
}

#reset_startnil

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.

Returns:

  • (nil)


594
595
596
597
598
599
600
601
# File 'ext/pg_connection.c', line 594

static VALUE
pgconn_reset_start(VALUE self)
{
	pgconn_close_socket_io( self );
	if(gvl_PQresetStart(pg_get_pgconn(self)) == 0)
		rb_raise(rb_eUnableToSend, "reset has failed");
	return Qnil;
}

#send_describe_portal(portal_name) ⇒ nil

Asynchronously send command to the server. Does not block. Use in combination with conn.get_result.

Returns:

  • (nil)


2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
# File 'ext/pg_connection.c', line 2059

static VALUE
pgconn_send_describe_portal(VALUE self, VALUE portal)
{
	VALUE error;
	PGconn *conn = pg_get_pgconn(self);
	/* returns 0 on failure */
	if(gvl_PQsendDescribePortal(conn, pg_cstr_enc(portal, ENCODING_GET(self))) == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

#send_describe_prepared(statement_name) ⇒ nil

Asynchronously send command to the server. Does not block. Use in combination with conn.get_result.

Returns:

  • (nil)


2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
# File 'ext/pg_connection.c', line 2037

static VALUE
pgconn_send_describe_prepared(VALUE self, VALUE stmt_name)
{
	VALUE error;
	PGconn *conn = pg_get_pgconn(self);
	/* returns 0 on failure */
	if(gvl_PQsendDescribePrepared(conn, pg_cstr_enc(stmt_name, ENCODING_GET(self))) == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

#send_prepare(stmt_name, sql[, param_types ]) ⇒ nil

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, $1, $2, etc., inside the SQL query.

Returns:

  • (nil)


1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
# File 'ext/pg_connection.c', line 1918

static VALUE
pgconn_send_prepare(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	int result;
	VALUE name, command, in_paramtypes;
	VALUE param;
	VALUE error;
	int i = 0;
	int nParams = 0;
	Oid *paramTypes = NULL;
	const char *name_cstr;
	const char *command_cstr;
	int enc_idx = ENCODING_GET(self);

	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(conn, name_cstr, command_cstr, nParams, paramTypes);

	xfree(paramTypes);

	if(result == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

#send_query(sql[, params, result_format[, type_map ]]) ⇒ nil

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 optional 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, $1, $2, 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.

Returns:

  • (nil)


1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
# File 'ext/pg_connection.c', line 1853

static VALUE
pgconn_send_query(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	int result;
	VALUE command, in_res_fmt;
	VALUE error;
	int nParams;
	int resultFormat;
	struct query_params_data paramsData = { ENCODING_GET(self) };

	rb_scan_args(argc, argv, "13", &command, &paramsData.params, &in_res_fmt, &paramsData.typemap);
	paramsData.with_types = 1;

	/* If called with no parameters, use PQsendQuery */
	if(NIL_P(paramsData.params)) {
		if(gvl_PQsendQuery(conn, pg_cstr_enc(command, paramsData.enc_idx)) == 0) {
			error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
			rb_iv_set(error, "@connection", self);
			rb_exc_raise(error);
		}
		return Qnil;
	}

	/* If called with parameters, and optionally result_format,
	 * use PQsendQueryParams
	 */

	pgconn_query_assign_typemap( self, &paramsData );
	resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
	nParams = alloc_query_params( &paramsData );

	result = gvl_PQsendQueryParams(conn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
		(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);

	free_query_params( &paramsData );

	if(result == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

#send_query_prepared(statement_name[, params, result_format[, type_map ]]) ⇒ Object #-Object

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, $1, $2, 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.



1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
# File 'ext/pg_connection.c', line 1993

static VALUE
pgconn_send_query_prepared(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	int result;
	VALUE name, in_res_fmt;
	VALUE error;
	int nParams;
	int resultFormat;
	struct query_params_data paramsData = { ENCODING_GET(self) };

	rb_scan_args(argc, argv, "13", &name, &paramsData.params, &in_res_fmt, &paramsData.typemap);
	paramsData.with_types = 0;

	if(NIL_P(paramsData.params)) {
		paramsData.params = rb_ary_new2(0);
		resultFormat = 0;
	}
	pgconn_query_assign_typemap( self, &paramsData );

	resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
	nParams = alloc_query_params( &paramsData );

	result = gvl_PQsendQueryPrepared(conn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
		(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
		resultFormat);

	free_query_params( &paramsData );

	if(result == 0) {
		error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}
	return Qnil;
}

#server_versionInteger

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.

Returns:

  • (Integer)


823
824
825
826
827
# File 'ext/pg_connection.c', line 823

static VALUE
pgconn_server_version(VALUE self)
{
	return INT2NUM(PQserverVersion(pg_get_pgconn(self)));
}

#set_client_encoding(encoding) ⇒ Object Also known as: client_encoding=

Sets the client encoding to the encoding String.



2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
# File 'ext/pg_connection.c', line 2937

static VALUE
pgconn_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 ) {
		rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn));
	}
	pgconn_set_internal_encoding_index( self );

	return Qnil;
}

#set_default_encodingEncoding

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.

Returns:

  • (Encoding)


3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
# File 'ext/pg_connection.c', line 3683

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, encname) != 0 )
			rb_warn( "Failed to set the default_internal encoding to %s: '%s'",
			         encname, PQerrorMessage(conn) );
		pgconn_set_internal_encoding_index( self );
		return rb_enc_from_encoding( enc );
	} else {
		pgconn_set_internal_encoding_index( self );
		return Qnil;
	}
}

#set_error_verbosity(verbosity) ⇒ Integer

Sets connection’s verbosity to verbosity and returns the previous setting. Available settings are:

  • PQERRORS_TERSE

  • PQERRORS_DEFAULT

  • PQERRORS_VERBOSE

Returns:

  • (Integer)


2709
2710
2711
2712
2713
2714
2715
# File 'ext/pg_connection.c', line 2709

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));
}

#set_notice_processor {|message| ... } ⇒ Proc

See #set_notice_receiver for the desription 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.

Yields:

  • (message)

Returns:

  • (Proc)


2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
# File 'ext/pg_connection.c', line 2888

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;
}

#set_notice_receiver {|result| ... } ⇒ 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.

Yields:

  • (result)

Returns:

  • (Proc)


2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
# File 'ext/pg_connection.c', line 2828

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;
}

#set_single_row_modeself

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

Available since PostgreSQL-9.2

Returns:

  • (self)


1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
# File 'ext/pg_connection.c', line 1799

static VALUE
pgconn_set_single_row_mode(VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	VALUE error;

	if( PQsetSingleRowMode(conn) == 0 )
	{
		error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}

	return self;
}

#setnonblocking(Boolean) ⇒ nil

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.

Returns:

  • (nil)


2161
2162
2163
# File 'ext/pg_connection.c', line 2161

static VALUE
pgconn_setnonblocking(self, state)
VALUE self, state;

#socketInteger

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.

Returns:

  • (Integer)


860
861
862
863
864
865
866
867
# File 'ext/pg_connection.c', line 860

static VALUE
pgconn_socket(VALUE self)
{
	int sd;
	if( (sd = PQsocket(pg_get_pgconn(self))) < 0)
		rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor");
	return INT2NUM(sd);
}

#socket_ioObject

Fetch a memorized IO object created from the Connection’s underlying socket. This object can be used for IO.select to wait for events while running asynchronous API calls.

Using this instead of #socket 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. In contrast to #socket, it also works on Windows.



881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
# File 'ext/pg_connection.c', line 881

static VALUE
pgconn_socket_io(VALUE self)
{
	int sd;
	int ruby_sd;
	ID id_autoclose = rb_intern("autoclose=");
	t_pg_connection *this = pg_get_connection_safe( self );
	VALUE socket_io = this->socket_io;

	if ( !RTEST(socket_io) ) {
		if( (sd = PQsocket(this->pgconn)) < 0)
			rb_raise(rb_eConnectionBad, "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);
		#else
			ruby_sd = sd;
		#endif

		socket_io = rb_funcall( rb_cIO, rb_intern("for_fd"), 1, INT2NUM(ruby_sd) );

		/* Disable autoclose feature, when supported */
		if( rb_respond_to(socket_io, id_autoclose) ){
			rb_funcall( socket_io, id_autoclose, 1, Qfalse );
		}

		this->socket_io = socket_io;
	}

	return socket_io;
}

#ssl_attribute(attribute_name) ⇒ String

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 www.postgresql.org/docs/current/interactive/libpq-status.html#LIBPQ-PQSSLATTRIBUTE

Available since PostgreSQL-9.5

Returns:

  • (String)


3215
3216
3217
3218
3219
3220
3221
3222
# File 'ext/pg_connection.c', line 3215

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;
}

#ssl_attribute_namesArray<String>

Return an array of SSL attribute names available.

See also #ssl_attribute

Available since PostgreSQL-9.5

Returns:

  • (Array<String>)


3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
# File 'ext/pg_connection.c', line 3234

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;
}

#ssl_attributesObject

call-seq:

conn.ssl_attributes -> Hash<String,String>

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



264
265
266
267
268
# File 'lib/pg/connection.rb', line 264

def ssl_attributes
	ssl_attribute_names.each.with_object({}) do |n,h|
		h[n] = ssl_attribute(n)
	end
end

#ssl_in_use?Boolean

Returns true if the connection uses SSL, false if not.

Available since PostgreSQL-9.5

Returns:

  • (Boolean)


3181
3182
3183
3184
3185
# File 'ext/pg_connection.c', line 3181

static VALUE
pgconn_ssl_in_use(VALUE self)
{
	return PQsslInUse(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}

#statusObject

Returns status of connection : CONNECTION_OK or CONNECTION_BAD



747
748
749
750
751
# File 'ext/pg_connection.c', line 747

static VALUE
pgconn_status(VALUE self)
{
	return INT2NUM(PQstatus(pg_get_pgconn(self)));
}

#trace(stream) ⇒ nil

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.

Returns:

  • (nil)


2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
# File 'ext/pg_connection.c', line 2726

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")) == Qfalse)
		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;
}

#transaction {|conn| ... } ⇒ Object

Executes a BEGIN at the start of the block, and a COMMIT at the end of the block, or ROLLBACK if any exception occurs.

Yields:

  • (conn)


2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
# File 'ext/pg_connection.c', line 2960

static VALUE
pgconn_transaction(VALUE self)
{
	PGconn *conn = pg_get_pgconn(self);
	PGresult *result;
	VALUE rb_pgresult;
	VALUE block_result = Qnil;
	int status;

	if (rb_block_given_p()) {
		result = gvl_PQexec(conn, "BEGIN");
		rb_pgresult = pg_new_result(result, self);
		pg_result_check(rb_pgresult);
		block_result = rb_protect(rb_yield, self, &status);
		if(status == 0) {
			result = gvl_PQexec(conn, "COMMIT");
			rb_pgresult = pg_new_result(result, self);
			pg_result_check(rb_pgresult);
		}
		else {
			/* exception occurred, ROLLBACK and re-raise */
			result = gvl_PQexec(conn, "ROLLBACK");
			rb_pgresult = pg_new_result(result, self);
			pg_result_check(rb_pgresult);
			rb_jump_tag(status);
		}

	}
	else {
		/* no block supplied? */
		rb_raise(rb_eArgError, "Must supply block for PG::Connection#transaction");
	}
	return block_result;
}

#transaction_statusObject

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)


764
765
766
767
768
# File 'ext/pg_connection.c', line 764

static VALUE
pgconn_transaction_status(VALUE self)
{
	return INT2NUM(PQtransactionStatus(pg_get_pgconn(self)));
}

#ttyObject

Returns the connected pgtty. (Obsolete)



695
696
697
698
699
700
701
# File 'ext/pg_connection.c', line 695

static VALUE
pgconn_tty(VALUE self)
{
	char *tty = PQtty(pg_get_pgconn(self));
	if (!tty) return Qnil;
	return rb_tainted_str_new2(tty);
}

#type_map_for_queriesTypeMap

Returns the default TypeMap that is currently set for type casts of query bind parameters.

Returns:



3736
3737
3738
3739
3740
3741
3742
# File 'ext/pg_connection.c', line 3736

static VALUE
pgconn_type_map_for_queries_get(VALUE self)
{
	t_pg_connection *this = pg_get_connection( self );

	return this->type_map_for_queries;
}

#type_map_for_queries=(typemap) ⇒ Object

Set the default TypeMap that is used for type casts of query bind parameters.

typemap must be a kind of PG::TypeMap .



3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
# File 'ext/pg_connection.c', line 3713

static VALUE
pgconn_type_map_for_queries_set(VALUE self, VALUE typemap)
{
	t_pg_connection *this = pg_get_connection( self );

	if ( !rb_obj_is_kind_of(typemap, rb_cTypeMap) ) {
		rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::TypeMap)",
				rb_obj_classname( typemap ) );
	}
	Check_Type(typemap, T_DATA);
	this->type_map_for_queries = typemap;

	return typemap;
}

#type_map_for_resultsTypeMap

Returns the default TypeMap that is currently set for type casts of result values.

Returns:



3775
3776
3777
3778
3779
3780
3781
# File 'ext/pg_connection.c', line 3775

static VALUE
pgconn_type_map_for_results_get(VALUE self)
{
	t_pg_connection *this = pg_get_connection( self );

	return this->type_map_for_results;
}

#type_map_for_results=(typemap) ⇒ Object

Set the default TypeMap that is used for type casts of result values.

typemap must be a kind of PG::TypeMap .



3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
# File 'ext/pg_connection.c', line 3753

static VALUE
pgconn_type_map_for_results_set(VALUE self, VALUE typemap)
{
	t_pg_connection *this = pg_get_connection( self );

	if ( !rb_obj_is_kind_of(typemap, rb_cTypeMap) ) {
		rb_raise( rb_eTypeError, "wrong argument type %s (expected kind of PG::TypeMap)",
				rb_obj_classname( typemap ) );
	}
	Check_Type(typemap, T_DATA);
	this->type_map_for_results = typemap;

	return typemap;
}

#PG::Connection.unescape_bytea(string) ⇒ Object

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.



1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
# File 'ext/pg_connection.c', line 1661

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);
	OBJ_INFECT(ret, str);
	PQfreemem(to);
	return ret;
}

#untracenil

Disables the message tracing.

Returns:

  • (nil)


2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
# File 'ext/pg_connection.c', line 2768

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;
}

#userObject

Returns the authenticated user name.



640
641
642
643
644
645
646
# File 'ext/pg_connection.c', line 640

static VALUE
pgconn_user(VALUE self)
{
	char *user = PQuser(pg_get_pgconn(self));
	if (!user) return Qnil;
	return rb_tainted_str_new2(user);
}

#wait_for_notify([ timeout ]) ⇒ String #wait_for_notify([ timeout ]) {|event, pid| ... } ⇒ Object #wait_for_notify([ timeout ]) ⇒ Object Also known as: notifies_wait

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 and the generating pid into the block.

Under PostgreSQL 9.0 and later, if the notification is sent with the optional payload string, it will be given to the block as the third argument.

Overloads:

  • #wait_for_notify([ timeout ]) ⇒ String

    Returns:

    • (String)
  • #wait_for_notify([ timeout ]) {|event, pid| ... } ⇒ Object

    Yields:

    • (event, pid)


2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
# File 'ext/pg_connection.c', line 2478

static VALUE
pgconn_wait_for_notify(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = pg_get_pgconn( 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( conn, ptimeout, notify_readable);

	/* Return nil if the select timed out */
	if ( !pnotification ) return Qnil;

	relname = rb_tainted_str_new2( pnotification->relname );
	PG_ENCODING_SET_NOCHECK( relname, ENCODING_GET(self) );
	be_pid = INT2NUM( pnotification->be_pid );
	if ( *pnotification->extra ) {
		extra = rb_tainted_str_new2( pnotification->extra );
		PG_ENCODING_SET_NOCHECK( extra, ENCODING_GET(self) );
	}
	PQfreemem( pnotification );

	if ( rb_block_given_p() )
		rb_yield_values( 3, relname, be_pid, extra );

	return relname;
}