Class: PGconn

Inherits:
Object
  • Object
show all
Defined in:
ext/pg.c,
ext/pg.c

Overview

******************************************************************

The class to access PostgreSQL RDBMS, based on the libpq interface,
provides convenient OO methods to interact with PostgreSQL.

For example, to send query to the database on the localhost:
   require 'pg'
   conn = PGconn.open(:dbname => 'test')
   res = conn.exec('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 PGresult class for information on working with the results of a query.

Constant Summary collapse

VERSION =

Library version

rb_str_new2(VERSION)
CONNECTION_OK =

Connection succeeded

INT2FIX(CONNECTION_OK)
CONNECTION_BAD =

Connection failed

INT2FIX(CONNECTION_BAD)
CONNECTION_STARTED =

Waiting for connection to be made.

INT2FIX(CONNECTION_STARTED)
CONNECTION_MADE =

Connection OK; waiting to send.

INT2FIX(CONNECTION_MADE)
CONNECTION_AWAITING_RESPONSE =

Waiting for a response from the server.

INT2FIX(CONNECTION_AWAITING_RESPONSE)
CONNECTION_AUTH_OK =

Received authentication; waiting for backend start-up to finish.

INT2FIX(CONNECTION_AUTH_OK)
CONNECTION_SSL_STARTUP =

Negotiating SSL encryption.

INT2FIX(CONNECTION_SSL_STARTUP)
CONNECTION_SETENV =

Negotiating environment-driven parameter settings.

INT2FIX(CONNECTION_SETENV)
PGRES_POLLING_READING =

Async connection is waiting to read

INT2FIX(PGRES_POLLING_READING)
PGRES_POLLING_WRITING =

Async connection is waiting to write

INT2FIX(PGRES_POLLING_WRITING)
PGRES_POLLING_FAILED =

Async connection failed or was reset

INT2FIX(PGRES_POLLING_FAILED)
PGRES_POLLING_OK =

Async connection succeeded

INT2FIX(PGRES_POLLING_OK)
PQTRANS_IDLE =

Transaction is currently idle (#transaction_status)

INT2FIX(PQTRANS_IDLE)
PQTRANS_ACTIVE =

Transaction is currently active; query has been sent to the server, but not yet completed. (#transaction_status)

INT2FIX(PQTRANS_ACTIVE)
PQTRANS_INTRANS =

Transaction is currently idle, in a valid transaction block (#transaction_status)

INT2FIX(PQTRANS_INTRANS)
PQTRANS_INERROR =

Transaction is currently idle, in a failed transaction block (#transaction_status)

INT2FIX(PQTRANS_INERROR)
PQTRANS_UNKNOWN =

Transaction’s connection is bad (#transaction_status)

INT2FIX(PQTRANS_UNKNOWN)
PQERRORS_TERSE =

Terse error verbosity level (#set_error_verbosity)

INT2FIX(PQERRORS_TERSE)
PQERRORS_DEFAULT =

Default error verbosity level (#set_error_verbosity)

INT2FIX(PQERRORS_DEFAULT)
PQERRORS_VERBOSE =

Verbose error verbosity level (#set_error_verbosity)

INT2FIX(PQERRORS_VERBOSE)
INV_WRITE =

Flag for #lo_creat, #lo_open – open for writing

INT2FIX(INV_WRITE)
INV_READ =

Flag for #lo_creat, #lo_open – open for reading

INT2FIX(INV_READ)
SEEK_SET =

Flag for #lo_lseek – seek from object start

INT2FIX(SEEK_SET)
SEEK_CUR =

Flag for #lo_lseek – seek from current position

INT2FIX(SEEK_CUR)
SEEK_END =

Flag for #lo_lseek – seek from object end

INT2FIX(SEEK_END)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Object

call-seq:

PGconn.new(connection_hash) -> PGconn
PGconn.new(connection_string) -> PGconn
PGconn.new(host, port, options, tty, dbname, login, password) ->  PGconn

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:

# As a Hash
PGconn.connect( :dbname => 'test', :port => 5432 )

# As a String
PGconn.connect( "dbname=test port=5432" )

# As an Array
PGconn.connect( 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.



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'ext/pg.c', line 398

static VALUE
pgconn_init(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = NULL;
	VALUE conninfo;
	VALUE error;
#ifdef M17N_SUPPORTED	
	rb_encoding *enc;
	const char *encname;
#endif

	conninfo = parse_connect_args(argc, argv, self);
	conn = PQconnectdb(StringValuePtr(conninfo));

	if(conn == NULL)
		rb_raise(rb_ePGError, "PQconnectStart() unable to allocate structure");

	Check_Type(self, T_DATA);
	DATA_PTR(self) = conn;

	if (PQstatus(conn) == CONNECTION_BAD) {
		error = rb_exc_new2(rb_ePGError, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}

#ifdef M17N_SUPPORTED
	/* If Ruby has its Encoding.default_internal set, set PostgreSQL's client_encoding 
	 * to match */
	if (( enc = rb_default_internal_encoding() )) {
		encname = pgconn_get_rb_encoding_as_pg_encname( enc );
		if ( PQsetClientEncoding(conn, encname) != 0 )
			rb_warn( "Failed to set the default_internal encoding to %s: '%s'",
			         encname, PQerrorMessage(conn) );
	}
#endif

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

Class Method Details

.conndefaultsArray

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

Returns:

  • (Array)


511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'ext/pg.c', line 511

static VALUE
pgconn_s_conndefaults(VALUE self)
{
	PQconninfoOption *options = PQconndefaults();
	VALUE ary = rb_ary_new();
	VALUE hash;
	int i = 0;

	for(i = 0; options[i].keyword != NULL; i++) {
		hash = rb_hash_new();
		if(options[i].keyword)
			rb_hash_aset(hash, ID2SYM(rb_intern("keyword")), 
				rb_str_new2(options[i].keyword));
		if(options[i].envvar)
			rb_hash_aset(hash, ID2SYM(rb_intern("envvar")), 
				rb_str_new2(options[i].envvar));
		if(options[i].compiled)
			rb_hash_aset(hash, ID2SYM(rb_intern("compiled")), 
				rb_str_new2(options[i].compiled));
		if(options[i].val)
			rb_hash_aset(hash, ID2SYM(rb_intern("val")), 
				rb_str_new2(options[i].val));
		if(options[i].label)
			rb_hash_aset(hash, ID2SYM(rb_intern("label")), 
				rb_str_new2(options[i].label));
		if(options[i].dispchar)
			rb_hash_aset(hash, ID2SYM(rb_intern("dispchar")), 
				rb_str_new2(options[i].dispchar));
		rb_hash_aset(hash, ID2SYM(rb_intern("dispsize")), 
			INT2NUM(options[i].dispsize));
		rb_ary_push(ary, hash);
	}
	PQconninfoFree(options);
	return ary;
}

.connect_start(connection_hash) ⇒ PGconn .connect_start(connection_string) ⇒ PGconn .connect_start(host, port, options, tty, dbname, login, password) ⇒ PGconn

This is an asynchronous version of PGconn.connect().

Use PGconn#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 PGconn#internal_encoding=. You can also set it automatically by setting ENV, or include the ‘options’ connection parameter.

Overloads:

  • .connect_start(connection_hash) ⇒ PGconn

    Returns:

  • .connect_start(connection_string) ⇒ PGconn

    Returns:

  • .connect_start(host, port, options, tty, dbname, login, password) ⇒ PGconn

    Returns:



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'ext/pg.c', line 457

static VALUE
pgconn_s_connect_start(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = NULL;
	VALUE rb_conn;
	VALUE conninfo;
	VALUE error;

	/*
	 * PGconn.connect_start must act as both alloc() and initialize()
	 * because it is not invoked by calling new().
	 */
	rb_conn = pgconn_alloc(rb_cPGconn);

	conninfo = parse_connect_args(argc, argv, self);
	conn = PQconnectStart(StringValuePtr(conninfo));

	if(conn == NULL)
		rb_raise(rb_ePGError, "PQconnectStart() unable to allocate structure");
	if (PQstatus(conn) == CONNECTION_BAD) {
		error = rb_exc_new2(rb_ePGError, PQerrorMessage(conn));
		rb_iv_set(error, "@connection", self);
		rb_exc_raise(error);
	}

	Check_Type(rb_conn, T_DATA);
	DATA_PTR(rb_conn) = conn;

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

.encrypt_password(password, username) ⇒ String

This function is intended to be used by client applications that send commands like: ALTER USER joe PASSWORD ‘pwd’. The arguments are the cleartext password, and the SQL name of the user it is for.

Return value is the encrypted password.

Returns:

  • (String)


559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'ext/pg.c', line 559

static VALUE
pgconn_s_encrypt_password(VALUE self, VALUE password, VALUE username)
{
	char *encrypted = NULL;
	VALUE rval = Qnil;

	Check_Type(password, T_STRING);
	Check_Type(username, T_STRING);

	encrypted = PQencryptPassword(StringValuePtr(password), StringValuePtr(username));
	rval = rb_str_new2( encrypted );
	PQfreemem( encrypted );

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

	return rval;
}

.escape_bytea(string) ⇒ String .escape_bytea(string) ⇒ String #DEPRECATEDD

Connection instance method for versions of 8.1 and higher of libpq uses PQescapeByteaConn, which is safer. Avoid calling as a class method, the class method uses the deprecated PQescapeBytea() API function.

Use the instance method version of this function, it is safer than the class method.

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.

Overloads:

  • .escape_bytea(string) ⇒ String

    Returns:

    • (String)
  • .escape_bytea(string) ⇒ String #DEPRECATEDD

    Returns:

    • (String #DEPRECATEDD)


1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
# File 'ext/pg.c', line 1468

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_class(self) == rb_cPGconn) {
		to = PQescapeByteaConn(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 .escape_string(str) ⇒ String #DEPRECATEDD

Connection instance method for versions of 8.1 and higher of libpq uses PQescapeStringConn, which is safer. Avoid calling as a class method, the class method uses the deprecated PQescapeString() API function.

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.

Overloads:

  • .escape_string(str) ⇒ String

    Returns:

    • (String)
  • .escape_string(str) ⇒ String #DEPRECATEDD

    Returns:

    • (String #DEPRECATEDD)


1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
# File 'ext/pg.c', line 1403

static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
	char *escaped;
	int size,error;
	VALUE result;
#ifdef M17N_SUPPORTED	
	rb_encoding* enc;
#endif

	Check_Type(string, T_STRING);

	escaped = ALLOC_N(char, RSTRING_LEN(string) * 2 + 1);
	if(rb_obj_class(self) == rb_cPGconn) {
		size = PQescapeStringConn(get_pgconn(self), escaped, 
			RSTRING_PTR(string), RSTRING_LEN(string), &error);
		if(error) {
			xfree(escaped);
			rb_raise(rb_ePGError, "%s", PQerrorMessage(get_pgconn(self)));
		}
	} else {
		size = PQescapeString(escaped, RSTRING_PTR(string),
			RSTRING_LEN(string));
	}
	result = rb_str_new(escaped, size);
	xfree(escaped);
	OBJ_INFECT(result, string);

#ifdef M17N_SUPPORTED
	if(rb_obj_class(self) == rb_cPGconn) {
		enc = pgconn_get_client_encoding_as_rb_encoding(get_pgconn(self));
	} else {
		enc = rb_enc_get(string);
	}
	rb_enc_associate(result, enc);
#endif

	return result;
}

.isthreadsafeBoolean

Returns true if libpq is thread safe, false otherwise.

Returns:

  • (Boolean)


585
586
587
588
589
# File 'ext/pg.c', line 585

static VALUE
pgconn_s_isthreadsafe(VALUE self)
{
	return PQisthreadsafe() ? Qtrue : Qfalse;
}

.quote_ident(str) ⇒ String .quote_ident(str) ⇒ 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 PGconn.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.

Overloads:

  • .quote_ident(str) ⇒ String

    Returns:

    • (String)
  • .quote_ident(str) ⇒ String

    Returns:

    • (String)


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
# File 'ext/pg.c', line 2552

static VALUE
pgconn_s_quote_ident(VALUE self, VALUE in_str)
{
	VALUE ret;
	char *str = StringValuePtr(in_str);
	/* result size at most NAMEDATALEN*2 plus surrounding
	 * double-quotes. */
	char buffer[NAMEDATALEN*2+2];
	unsigned int i=0,j=0;

	if(strlen(str) >= NAMEDATALEN) {
		rb_raise(rb_eArgError, 
			"Input string is longer than NAMEDATALEN-1 (%d)",
			NAMEDATALEN-1);
	}
	buffer[j++] = '"';
	for(i = 0; i < strlen(str) && str[i]; i++) {
		if(str[i] == '"') 
			buffer[j++] = '"';
		buffer[j++] = str[i];
	}
	buffer[j++] = '"';
	ret = rb_str_new(buffer,j);
	OBJ_INFECT(ret, in_str);
	return ret;
}

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



1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
# File 'ext/pg.c', line 1501

static VALUE
pgconn_s_unescape_bytea(VALUE self, VALUE str)
{
	unsigned char *from, *to;
	size_t to_len;
	VALUE ret;

	Check_Type(str, T_STRING);
	from = (unsigned char*)StringValuePtr(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 ]) ⇒ PGresult #async_exec(sql[, params, result_format ]) {|pg_result| ... } ⇒ Object Also known as: async_query

This function has the same behavior as PGconn#exec, except that it’s implemented using asynchronous command processing and ruby’s rb_thread_select in order to allow other threads to process while waiting for the server to complete the request.

Overloads:

  • #async_exec(sql[, params, result_format ]) ⇒ PGresult

    Returns:

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

    Yields:

    • (pg_result)


2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
# File 'ext/pg.c', line 2693

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

	/* remove any remaining results from the queue */
	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, pgresult_clear, rb_pgresult );
	}
	return rb_pgresult;
}

#backend_pidFixnum

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

Returns:

  • (Fixnum)


923
924
925
926
927
# File 'ext/pg.c', line 923

static VALUE
pgconn_backend_pid(VALUE self)
{
	return INT2NUM(PQbackendPID(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)


2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
# File 'ext/pg.c', line 2593

static VALUE
pgconn_block( int argc, VALUE *argv, VALUE self ) {
	PGconn *conn = get_pgconn(self);
	int sd = PQsocket(conn);
	int ret;
	struct timeval timeout;
	struct timeval *ptimeout = NULL;
	VALUE timeout_in;
	double timeout_sec;
	fd_set sd_rset;

	/* Always set a timeout in WIN32, as rb_thread_select() sometimes
	 * doesn't return when a second ruby thread is running although data
	 * could be read. So we use timeout-based polling instead.
	 */
#if defined(_WIN32)
	timeout.tv_sec = 0;
	timeout.tv_usec = 10000;
	ptimeout = &timeout;
#endif

	if ( rb_scan_args(argc, argv, "01", &timeout_in) == 1 ) {
		timeout_sec = NUM2DBL( timeout_in );
		timeout.tv_sec = (long)timeout_sec;
		timeout.tv_usec = (long)((timeout_sec - (long)timeout_sec) * 1e6);
		ptimeout = &timeout;
	}

	PQconsumeInput( conn );

	while ( PQisBusy(conn) ) {
		FD_ZERO( &sd_rset );
		FD_SET( sd, &sd_rset );
		ret = rb_thread_select( sd+1, &sd_rset, NULL, NULL, ptimeout );

		/* Return false if there was a timeout argument and the select() timed out */
		if ( ret == 0 && argc ) 
			return Qfalse;

		PQconsumeInput( conn );
	} 

	return Qtrue;
}

#cancelString

Requests cancellation of the command currently being processed.

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

Returns:

  • (String)


2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
# File 'ext/pg.c', line 2054

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

	cancel = PQgetCancel(get_pgconn(self));
	if(cancel == NULL)
		rb_raise(rb_ePGError,"Invalid connection!");

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

	PQfreeCancel(cancel);
	return retval;
}

#conndefaultsArray

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

Returns:

  • (Array)


511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'ext/pg.c', line 511

static VALUE
pgconn_s_conndefaults(VALUE self)
{
	PQconninfoOption *options = PQconndefaults();
	VALUE ary = rb_ary_new();
	VALUE hash;
	int i = 0;

	for(i = 0; options[i].keyword != NULL; i++) {
		hash = rb_hash_new();
		if(options[i].keyword)
			rb_hash_aset(hash, ID2SYM(rb_intern("keyword")), 
				rb_str_new2(options[i].keyword));
		if(options[i].envvar)
			rb_hash_aset(hash, ID2SYM(rb_intern("envvar")), 
				rb_str_new2(options[i].envvar));
		if(options[i].compiled)
			rb_hash_aset(hash, ID2SYM(rb_intern("compiled")), 
				rb_str_new2(options[i].compiled));
		if(options[i].val)
			rb_hash_aset(hash, ID2SYM(rb_intern("val")), 
				rb_str_new2(options[i].val));
		if(options[i].label)
			rb_hash_aset(hash, ID2SYM(rb_intern("label")), 
				rb_str_new2(options[i].label));
		if(options[i].dispchar)
			rb_hash_aset(hash, ID2SYM(rb_intern("dispchar")), 
				rb_str_new2(options[i].dispchar));
		rb_hash_aset(hash, ID2SYM(rb_intern("dispsize")), 
			INT2NUM(options[i].dispsize));
		rb_ary_push(ary, hash);
	}
	PQconninfoFree(options);
	return ary;
}

#connect_pollFixnum

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 = PGconn.connect_start("dbname=mydatabase")
socket = IO.for_fd(conn.socket)
status = conn.connect_poll
while(status != PGconn::PGRES_POLLING_OK) do
  # do some work while waiting for the connection to complete
  if(status == PGconn::PGRES_POLLING_READING)
    if(not select([socket], [], [], 10.0))
      raise "Asynchronous connection timed out!"
    end
  elsif(status == PGconn::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:

  • (Fixnum)


629
630
631
632
633
634
635
# File 'ext/pg.c', line 629

static VALUE
pgconn_connect_poll(VALUE self)
{
	PostgresPollingStatusType status;
	status = PQconnectPoll(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)


936
937
938
939
940
# File 'ext/pg.c', line 936

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

#connection_used_passwordBoolean

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

Returns:

  • (Boolean)


949
950
951
952
953
# File 'ext/pg.c', line 949

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

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



1936
1937
1938
# File 'ext/pg.c', line 1936

static VALUE
pgconn_consume_input(self)
VALUE self;

#dbObject

Returns the connected database name.



705
706
707
708
709
710
711
# File 'ext/pg.c', line 705

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

#describe_portal(portal_name) ⇒ PGresult

Retrieve information about the portal portal_name.

Returns:



1335
1336
1337
# File 'ext/pg.c', line 1335

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

#describe_prepared(statement_name) ⇒ PGresult

Retrieve information about the prepared statement statement_name.

Returns:



1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
# File 'ext/pg.c', line 1308

static VALUE
pgconn_describe_prepared(VALUE self, VALUE stmt_name)
{
	PGresult *result;
	VALUE rb_pgresult;
	PGconn *conn = get_pgconn(self);
	char *stmt;
	if(stmt_name == Qnil) {
		stmt = NULL;
	}
	else {
		Check_Type(stmt_name, T_STRING);
		stmt = StringValuePtr(stmt_name);
	}
	result = PQdescribePrepared(conn, stmt);
	rb_pgresult = new_pgresult(result, conn);
	pgresult_check(self, rb_pgresult);
	return rb_pgresult;
}

#errorString

Returns the error message about connection.

Returns:

  • (String)


891
892
893
894
895
896
897
# File 'ext/pg.c', line 891

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

#escape_bytea(string) ⇒ String #escape_bytea(string) ⇒ String #DEPRECATEDD

Connection instance method for versions of 8.1 and higher of libpq uses PQescapeByteaConn, which is safer. Avoid calling as a class method, the class method uses the deprecated PQescapeBytea() API function.

Use the instance method version of this function, it is safer than the class method.

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.

Overloads:

  • #escape_bytea(string) ⇒ String

    Returns:

    • (String)
  • #escape_bytea(string) ⇒ String #DEPRECATEDD

    Returns:

    • (String #DEPRECATEDD)


1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
# File 'ext/pg.c', line 1468

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_class(self) == rb_cPGconn) {
		to = PQescapeByteaConn(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 #escape_string(str) ⇒ String #DEPRECATEDD Also known as: escape

Connection instance method for versions of 8.1 and higher of libpq uses PQescapeStringConn, which is safer. Avoid calling as a class method, the class method uses the deprecated PQescapeString() API function.

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.

Overloads:

  • #escape_string(str) ⇒ String

    Returns:

    • (String)
  • #escape_string(str) ⇒ String #DEPRECATEDD

    Returns:

    • (String #DEPRECATEDD)


1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
# File 'ext/pg.c', line 1403

static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
	char *escaped;
	int size,error;
	VALUE result;
#ifdef M17N_SUPPORTED	
	rb_encoding* enc;
#endif

	Check_Type(string, T_STRING);

	escaped = ALLOC_N(char, RSTRING_LEN(string) * 2 + 1);
	if(rb_obj_class(self) == rb_cPGconn) {
		size = PQescapeStringConn(get_pgconn(self), escaped, 
			RSTRING_PTR(string), RSTRING_LEN(string), &error);
		if(error) {
			xfree(escaped);
			rb_raise(rb_ePGError, "%s", PQerrorMessage(get_pgconn(self)));
		}
	} else {
		size = PQescapeString(escaped, RSTRING_PTR(string),
			RSTRING_LEN(string));
	}
	result = rb_str_new(escaped, size);
	xfree(escaped);
	OBJ_INFECT(result, string);

#ifdef M17N_SUPPORTED
	if(rb_obj_class(self) == rb_cPGconn) {
		enc = pgconn_get_client_encoding_as_rb_encoding(get_pgconn(self));
	} else {
		enc = rb_enc_get(string);
	}
	rb_enc_associate(result, enc);
#endif

	return result;
}

#exec(sql[, params, result_format ]) ⇒ PGresult #exec(sql[, params, result_format ]) {|pg_result| ... } ⇒ Object Also known as: query

Sends SQL query request specified by sql to PostgreSQL. Returns a PGresult instance on success. On failure, it raises a PGError exception.

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   => Fixnum (oid of type of bind parameter)
   :format => Fixnum (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.

If the optional code block is given, it will be passed result as an argument, and the PGresult object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.

Overloads:

  • #exec(sql[, params, result_format ]) ⇒ PGresult

    Returns:

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

    Yields:

    • (pg_result)


995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
# File 'ext/pg.c', line 995

static VALUE
pgconn_exec(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;
	VALUE command, params, in_res_fmt;
	VALUE param, param_type, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_type, sym_value, sym_format;
	VALUE gc_array;
	int i=0;
	int nParams;
	Oid *paramTypes;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;

	rb_scan_args(argc, argv, "12", &command, &params, &in_res_fmt);

	Check_Type(command, T_STRING);

	/* If called with no parameters, use PQexec */
	if(NIL_P(params)) {
		result = PQexec(conn, StringValuePtr(command));
		rb_pgresult = new_pgresult(result, conn);
		pgresult_check(self, rb_pgresult);
		if (rb_block_given_p()) {
			return rb_ensure(rb_yield, rb_pgresult, 
				pgresult_clear, rb_pgresult);
		}
		return rb_pgresult;
	}

	/* If called with parameters, and optionally result_format,
	 * use PQexecParams
	 */
	Check_Type(params, T_ARRAY);

	if(NIL_P(in_res_fmt)) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);
	sym_type = ID2SYM(rb_intern("type"));
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = RARRAY_LEN(params);
	paramTypes = ALLOC_N(Oid, nParams); 
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);
	for(i = 0; i < nParams; i++) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_type = rb_hash_aref(param, sym_type);
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			param_type = Qnil;
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = Qnil;
		}

		if(param_type == Qnil)
			paramTypes[i] = 0;
		else
			paramTypes[i] = NUM2INT(param_type);

		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = PQexecParams(conn, StringValuePtr(command), nParams, paramTypes, 
		(const char * const *)paramValues, paramLengths, paramFormats, resultFormat);

	rb_gc_unregister_address(&gc_array);

	xfree(paramTypes);
	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

	rb_pgresult = new_pgresult(result, conn);
	pgresult_check(self, rb_pgresult);
	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, rb_pgresult, 
			pgresult_clear, rb_pgresult);
	}
	return rb_pgresult;
}

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

Execute prepared named statement specified by statement_name. Returns a PGresult instance on success. On failure, it raises a PGError exception.

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 => Fixnum (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.

If the optional code block is given, it will be passed result as an argument, and the PGresult 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 ]) ⇒ PGresult

    Returns:

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

    Yields:

    • (pg_result)


1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
# File 'ext/pg.c', line 1202

static VALUE
pgconn_exec_prepared(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = get_pgconn(self);
	PGresult *result = NULL;
	VALUE rb_pgresult;
	VALUE name, params, in_res_fmt;
	VALUE param, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_value, sym_format;
	VALUE gc_array;
	int i = 0;
	int nParams;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;


	rb_scan_args(argc, argv, "12", &name, &params, &in_res_fmt);
	Check_Type(name, T_STRING);

	if(NIL_P(params)) {
		params = rb_ary_new2(0);
		resultFormat = 0;
	}
	else {
		Check_Type(params, T_ARRAY);
	}

	if(NIL_P(in_res_fmt)) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = RARRAY_LEN(params);
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);
	for(i = 0; i < nParams; i++) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = INT2NUM(0);
		}
		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = PQexecPrepared(conn, StringValuePtr(name), nParams, 
		(const char * const *)paramValues, paramLengths, paramFormats, 
		resultFormat);

	rb_gc_unregister_address(&gc_array);

	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

	rb_pgresult = new_pgresult(result, conn);
	pgresult_check(self, rb_pgresult);
	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, rb_pgresult, 
			pgresult_clear, rb_pgresult);
	}
	return rb_pgresult;
}

#external_encodingEncoding

defined in Ruby 1.9 or later.

  • Returns the server_encoding of the connected database as a Ruby Encoding object.

  • Maps ‘SQL_ASCII’ to ASCII-8BIT.

Returns:

  • (Encoding)


3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
# File 'ext/pg.c', line 3901

static VALUE
pgconn_external_encoding(VALUE self)
{
	VALUE enc;
	enc = rb_iv_get(self, "@external_encoding");
	if (RTEST(enc)) {
		return enc;
	}
	else {
		int i;
		VALUE query = rb_usascii_str_new_cstr("SHOW server_encoding");
		VALUE pgresult = pgconn_exec(1, &query, self);
		VALUE enc_name = rb_ensure(enc_server_encoding_getvalue, pgresult, pgresult_clear, pgresult);

		if (strcmp("SQL_ASCII", StringValuePtr(enc_name)) == 0) {
			enc = rb_enc_from_encoding(rb_ascii8bit_encoding());
			goto cache;
		}
		for (i = 0; i < sizeof(enc_pg2ruby_mapping)/sizeof(enc_pg2ruby_mapping[0]); ++i) {
			if (strcmp(StringValuePtr(enc_name), enc_pg2ruby_mapping[i][0]) == 0) {
				enc = rb_enc_from_encoding(rb_enc_find(enc_pg2ruby_mapping[i][1]));
				goto cache;
			}
		}

		/* Ruby 1.9.1 does not supoort JOHAB */
		if (strcmp(StringValuePtr(enc_name), "JOHAB") == 0) {
			enc = rb_enc_from_encoding(find_or_create_johab());
			goto cache;
		}

		/* fallback */
		enc = rb_enc_from_encoding(rb_enc_find(StringValuePtr(enc_name)));
	}

cache:
	rb_iv_set(self, "@external_encoding", enc);
	return enc;
}

#finishObject Also known as: close

Closes the backend connection.



643
644
645
646
647
648
649
# File 'ext/pg.c', line 643

static VALUE
pgconn_finish(VALUE self)
{
	PQfinish(get_pgconn(self));
	DATA_PTR(self) = NULL;
	return Qnil;
}

#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 PGError exception if some other failure occurred.

Returns:

  • (Boolean)


2028
2029
2030
# File 'ext/pg.c', line 2028

static VALUE
pgconn_flush(self)
VALUE self;

#get_client_encodingString

Returns the client encoding as a String.

Returns:

  • (String)


2466
2467
2468
2469
2470
2471
# File 'ext/pg.c', line 2466

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

#get_copy_data([ async = false ]) ⇒ 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).

Returns:

  • (String)


2257
2258
2259
2260
2261
2262
2263
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
# File 'ext/pg.c', line 2257

static VALUE
pgconn_get_copy_data(int argc, VALUE *argv, VALUE self )
{
	VALUE async_in;
	VALUE error;
	VALUE result_str;
	int ret;
	int async;
	char *buffer;
	PGconn *conn = get_pgconn(self);

	if (rb_scan_args(argc, argv, "01", &async_in) == 0)
		async = 0;
	else
		async = (async_in == Qfalse || async_in == Qnil) ? 0 : 1;

	ret = PQgetCopyData(conn, &buffer, async);
	if(ret == -2) { // error
		error = rb_exc_new2(rb_ePGError, PQerrorMessage(conn));
		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;
	}
	result_str = rb_tainted_str_new(buffer, ret);
	PQfreemem(buffer);
	return result_str;
}

#get_last_resultPGresult

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 PGconn#get_result except that it is designed to get one and only one result.

Returns:



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
# File 'ext/pg.c', line 2653

static VALUE
pgconn_get_last_result(VALUE self)
{
	PGconn *conn = get_pgconn(self);
	VALUE rb_pgresult = Qnil;
	PGresult *cur, *prev;


	cur = prev = NULL;
	while ((cur = 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 = new_pgresult(prev, conn);
		pgresult_check(self, rb_pgresult);
	}

	return rb_pgresult;
}

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

Blocks waiting for the next result from a call to PGconn#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 PGresult object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.

Overloads:

  • #get_resultPGresult

    Returns:

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

    Yields:

    • (pg_result)


1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
# File 'ext/pg.c', line 1910

static VALUE
pgconn_get_result(VALUE self)
{
	PGconn *conn = get_pgconn(self);
	PGresult *result;
	VALUE rb_pgresult;

	result = PQgetResult(conn);
	if(result == NULL)
		return Qnil;
	rb_pgresult = new_pgresult(result, conn);
	if (rb_block_given_p()) {
		return rb_ensure(rb_yield, rb_pgresult,
			pgresult_clear, rb_pgresult);
	}
	return rb_pgresult;
}

#hostObject

Returns the connected server name.



747
748
749
750
751
752
753
# File 'ext/pg.c', line 747

static VALUE
pgconn_host(VALUE self)
{
	char *host = PQhost(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)


3826
3827
3828
3829
3830
# File 'ext/pg.c', line 3826

static VALUE
pgconn_internal_encoding(VALUE self)
{
	return rb_enc_from_encoding(pgconn_get_client_encoding_as_rb_encoding(get_pgconn(self)));
}

#internal_encoding=(value) ⇒ Object

A wrapper of PGconn#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 ‘SQL_ASCII’ to the client_encoding.



3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
# File 'ext/pg.c', line 3846

static VALUE
pgconn_internal_encoding_set(VALUE self, VALUE enc)
{
	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", RSTRING_PTR(enc)) == 0) {
		pgconn_set_client_encoding(self, rb_usascii_str_new_cstr("JOHAB"));
		return enc;
	}
	else {
		int i;
		const char *name; 
		name = rb_enc_name(rb_to_encoding(enc));

		/* sequential search becuase rarely called */
		for (i = 0; i < sizeof(enc_pg2ruby_mapping)/sizeof(enc_pg2ruby_mapping[0]); ++i) {
			if (strcmp(name, enc_pg2ruby_mapping[i][1]) == 0) {
				if (PQsetClientEncoding(get_pgconn(self), enc_pg2ruby_mapping[i][0]) == -1) {
					VALUE server_encoding = pgconn_external_encoding(self);
					rb_raise(rb_eEncCompatError, "imcompatible character encodings: %s and %s",
							rb_enc_name(rb_to_encoding(server_encoding)),
							enc_pg2ruby_mapping[i][0]);
				}
				return enc;
			}
		}

		/* Ruby 1.9.1 does not support JOHAB */
		if (strcasecmp(name, "JOHAB") == 0) {
			pgconn_set_client_encoding(self, rb_usascii_str_new_cstr("JOHAB"));
			return enc;
		}
	}

	enc = rb_inspect(enc);
	rb_raise(rb_ePGError, "unknown encoding: %s", StringValuePtr(enc));
}

#is_busyBoolean

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

Returns:

  • (Boolean)


1958
1959
1960
# File 'ext/pg.c', line 1958

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)


2011
2012
2013
# File 'ext/pg.c', line 2011

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)


2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
# File 'ext/pg.c', line 2976

static VALUE
pgconn_loclose(VALUE self, VALUE in_lo_desc)
{
	PGconn *conn = 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]) ⇒ Fixnum Also known as: locreat

Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PGError exception.

Returns:

  • (Fixnum)


2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
# File 'ext/pg.c', line 2723

static VALUE
pgconn_locreat(int argc, VALUE *argv, VALUE self)
{
	Oid lo_oid;
	int mode;
	VALUE nmode;
	PGconn *conn = 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 INT2FIX(lo_oid);
}

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

Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PGError exception.

Returns:

  • (Fixnum)


2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
# File 'ext/pg.c', line 2750

static VALUE
pgconn_locreate(VALUE self, VALUE in_lo_oid)
{
	Oid ret, lo_oid;
	PGconn *conn = get_pgconn(self);
	lo_oid = NUM2INT(in_lo_oid);

	ret = lo_create(conn, in_lo_oid);
	if (ret == InvalidOid)
		rb_raise(rb_ePGError, "lo_create failed");

	return INT2FIX(ret);
}

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

Saves a large object of oid to a file.

Returns:

  • (nil)


2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
# File 'ext/pg.c', line 2794

static VALUE
pgconn_loexport(VALUE self, VALUE lo_oid, VALUE filename)
{
	PGconn *conn = get_pgconn(self);
	int oid;
	Check_Type(filename, T_STRING);

	oid = NUM2INT(lo_oid);
	if (oid < 0) {
		rb_raise(rb_ePGError, "invalid large object oid %d",oid);
	}

	if (lo_export(conn, oid, StringValuePtr(filename)) < 0) {
		rb_raise(rb_ePGError, "%s", PQerrorMessage(conn));
	}
	return Qnil;
}

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

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

On failure, it raises a PGError exception.

Returns:

  • (Fixnum)


2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
# File 'ext/pg.c', line 2772

static VALUE
pgconn_loimport(VALUE self, VALUE filename)
{
	Oid lo_oid;

	PGconn *conn = get_pgconn(self);

	Check_Type(filename, T_STRING);

	lo_oid = lo_import(conn, StringValuePtr(filename));
	if (lo_oid == 0) {
		rb_raise(rb_ePGError, "%s", PQerrorMessage(conn));
	}
	return INT2FIX(lo_oid);
}

#lo_lseek(lo_desc, offset, whence) ⇒ Fixnum 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:

  • (Fixnum)


2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
# File 'ext/pg.c', line 2918

static VALUE
pgconn_lolseek(VALUE self, VALUE in_lo_desc, VALUE offset, VALUE whence)
{
	PGconn *conn = 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]) ⇒ Fixnum 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:

  • (Fixnum)


2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
# File 'ext/pg.c', line 2822

static VALUE
pgconn_loopen(int argc, VALUE *argv, VALUE self)
{
	Oid lo_oid;
	int fd, mode;
	VALUE nmode, selfid;
	PGconn *conn = get_pgconn(self);

	rb_scan_args(argc, argv, "11", &selfid, &nmode);
	lo_oid = NUM2INT(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)


2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
# File 'ext/pg.c', line 2877

static VALUE
pgconn_loread(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
	int ret;
  PGconn *conn = 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) ⇒ Fixnum Also known as: lotell

Returns the current position of the large object lo_desc.

Returns:

  • (Fixnum)


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

static VALUE
pgconn_lotell(VALUE self, VALUE in_lo_desc)
{
	int position;
	PGconn *conn = 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)


2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
# File 'ext/pg.c', line 2957

static VALUE
pgconn_lotruncate(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
	PGconn *conn = 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)


2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
# File 'ext/pg.c', line 2994

static VALUE
pgconn_lounlink(VALUE self, VALUE in_oid)
{
	PGconn *conn = get_pgconn(self);
	int oid = NUM2INT(in_oid);

	if (oid < 0)
		rb_raise(rb_ePGError, "invalid oid %d",oid);

	if(lo_unlink(conn,oid) < 0)
		rb_raise(rb_ePGError,"lo_unlink failed");

	return Qnil;
}

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

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

Returns:

  • (Fixnum)


2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
# File 'ext/pg.c', line 2850

static VALUE
pgconn_lowrite(VALUE self, VALUE in_lo_desc, VALUE buffer)
{
	int n;
	PGconn *conn = 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) ⇒ PGresult

Constructs and empty PGresult 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

Returns:



1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
# File 'ext/pg.c', line 1372

static VALUE
pgconn_make_empty_pgresult(VALUE self, VALUE status)
{
	PGresult *result;
	VALUE rb_pgresult;
	PGconn *conn = get_pgconn(self);
	result = PQmakeEmptyPGresult(conn, NUM2INT(status));
	rb_pgresult = new_pgresult(result, conn);
	pgresult_check(self, rb_pgresult);
	return rb_pgresult;
}

#notifiesObject

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



2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
# File 'ext/pg.c', line 2084

static VALUE
pgconn_notifies(VALUE self)
{
	PGconn* conn = 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 = 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(PGNOTIFY_EXTRA(notification));

	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.



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

static VALUE
pgconn_options(VALUE self)
{
	char *options = PQoptions(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)


843
844
845
846
847
848
849
850
851
852
# File 'ext/pg.c', line 843

static VALUE
pgconn_parameter_status(VALUE self, VALUE param_name)
{
	const char *ret = PQparameterStatus(get_pgconn(self), 
			StringValuePtr(param_name));
	if(ret == NULL)
		return Qnil;
	else
		return rb_tainted_str_new2(ret);
}

#passObject

Returns the authenticated user name.



733
734
735
736
737
738
739
# File 'ext/pg.c', line 733

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

#portObject

Returns the connected server port number.



761
762
763
764
765
766
# File 'ext/pg.c', line 761

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

#prepare(stmt_name, sql[, param_types ]) ⇒ PGresult

Prepares statement sql with name name to be executed later. Returns a PGresult instance on success. On failure, it raises a PGError exception.

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:



1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
# File 'ext/pg.c', line 1134

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

	rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
	Check_Type(name, T_STRING);
	Check_Type(command, T_STRING);

	if(! NIL_P(in_paramtypes)) {
		Check_Type(in_paramtypes, T_ARRAY);
		nParams = RARRAY_LEN(in_paramtypes);
		paramTypes = ALLOC_N(Oid, nParams); 
		for(i = 0; i < nParams; i++) {
			param = rb_ary_entry(in_paramtypes, i);
			Check_Type(param, T_FIXNUM);
			if(param == Qnil)
				paramTypes[i] = 0;
			else
				paramTypes[i] = NUM2INT(param);
		}
	}
	result = PQprepare(conn, StringValuePtr(name), StringValuePtr(command),
			nParams, paramTypes);

	xfree(paramTypes);

	rb_pgresult = new_pgresult(result, conn);
	pgresult_check(self, 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)


862
863
864
865
866
# File 'ext/pg.c', line 862

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

#put_copy_data(buffer) ⇒ 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).

Raises an exception if an error occurs.

Returns:

  • (Boolean)


2192
2193
2194
# File 'ext/pg.c', line 2192

static VALUE
pgconn_put_copy_data(self, buffer)
VALUE self, buffer;

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


2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
# File 'ext/pg.c', line 2225

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

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

	ret = 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(str) ⇒ 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 PGconn.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.

Overloads:

  • #quote_ident(str) ⇒ String

    Returns:

    • (String)
  • #quote_ident(str) ⇒ String

    Returns:

    • (String)


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
# File 'ext/pg.c', line 2552

static VALUE
pgconn_s_quote_ident(VALUE self, VALUE in_str)
{
	VALUE ret;
	char *str = StringValuePtr(in_str);
	/* result size at most NAMEDATALEN*2 plus surrounding
	 * double-quotes. */
	char buffer[NAMEDATALEN*2+2];
	unsigned int i=0,j=0;

	if(strlen(str) >= NAMEDATALEN) {
		rb_raise(rb_eArgError, 
			"Input string is longer than NAMEDATALEN-1 (%d)",
			NAMEDATALEN-1);
	}
	buffer[j++] = '"';
	for(i = 0; i < strlen(str) && str[i]; i++) {
		if(str[i] == '"') 
			buffer[j++] = '"';
		buffer[j++] = str[i];
	}
	buffer[j++] = '"';
	ret = rb_str_new(buffer,j);
	OBJ_INFECT(ret, in_str);
	return ret;
}

#resetObject

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



658
659
660
661
662
663
# File 'ext/pg.c', line 658

static VALUE
pgconn_reset(VALUE self)
{
	PQreset(get_pgconn(self));
	return self;
}

#reset_pollFixnum

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

Returns:

  • (Fixnum)


691
692
693
694
695
696
697
# File 'ext/pg.c', line 691

static VALUE
pgconn_reset_poll(VALUE self)
{
	PostgresPollingStatusType status;
	status = PQresetPoll(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 PGconn#reset_poll to check the status of the connection reset.

Returns:

  • (nil)


675
676
677
678
679
680
681
# File 'ext/pg.c', line 675

static VALUE
pgconn_reset_start(VALUE self)
{
	if(PQresetStart(get_pgconn(self)) == 0)
		rb_raise(rb_ePGError, "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)


1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
# File 'ext/pg.c', line 1879

static VALUE
pgconn_send_describe_portal(VALUE self, VALUE portal)
{
	VALUE error;
	PGconn *conn = get_pgconn(self);
	/* returns 0 on failure */
	if(PQsendDescribePortal(conn,StringValuePtr(portal)) == 0) {
		error = rb_exc_new2(rb_ePGError, 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)


1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
# File 'ext/pg.c', line 1857

static VALUE
pgconn_send_describe_prepared(VALUE self, VALUE stmt_name)
{
	VALUE error;
	PGconn *conn = get_pgconn(self);
	/* returns 0 on failure */
	if(PQsendDescribePrepared(conn,StringValuePtr(stmt_name)) == 0) {
		error = rb_exc_new2(rb_ePGError, 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 PGError exception.

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)


1685
1686
1687
1688
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
1718
1719
1720
1721
1722
1723
1724
1725
# File 'ext/pg.c', line 1685

static VALUE
pgconn_send_prepare(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = get_pgconn(self);
	int result;
	VALUE name, command, in_paramtypes;
	VALUE param;
	VALUE error;
	int i = 0;
	int nParams = 0;
	Oid *paramTypes = NULL;

	rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
	Check_Type(name, T_STRING);
	Check_Type(command, T_STRING);

	if(! NIL_P(in_paramtypes)) {
		Check_Type(in_paramtypes, T_ARRAY);
		nParams = RARRAY_LEN(in_paramtypes);
		paramTypes = ALLOC_N(Oid, nParams); 
		for(i = 0; i < nParams; i++) {
			param = rb_ary_entry(in_paramtypes, i);
			Check_Type(param, T_FIXNUM);
			if(param == Qnil)
				paramTypes[i] = 0;
			else
				paramTypes[i] = NUM2INT(param);
		}
	}
	result = PQsendPrepare(conn, StringValuePtr(name), StringValuePtr(command),
			nParams, paramTypes);

	xfree(paramTypes);

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

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

Sends SQL query request specified by sql to PostgreSQL for asynchronous processing, and immediately returns. On failure, it raises a PGError exception.

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   => Fixnum (oid of type of bind parameter)
   :format => Fixnum (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.

Returns:

  • (nil)


1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
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
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
# File 'ext/pg.c', line 1550

static VALUE
pgconn_send_query(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = get_pgconn(self);
	int result;
	VALUE command, params, in_res_fmt;
	VALUE param, param_type, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_type, sym_value, sym_format;
	VALUE gc_array;
	VALUE error;
	int i=0;
	int nParams;
	Oid *paramTypes;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;

	rb_scan_args(argc, argv, "12", &command, &params, &in_res_fmt);
	Check_Type(command, T_STRING);

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

	/* If called with parameters, and optionally result_format,
	 * use PQsendQueryParams
	 */
	Check_Type(params, T_ARRAY);

	if(NIL_P(in_res_fmt)) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);
	sym_type = ID2SYM(rb_intern("type"));
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = RARRAY_LEN(params);
	paramTypes = ALLOC_N(Oid, nParams); 
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);
	for(i = 0; i < nParams; i++) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_type = rb_hash_aref(param, sym_type);
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			param_type = INT2NUM(0);
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = INT2NUM(0);
		}

		if(param_type == Qnil)
			paramTypes[i] = 0;
		else
			paramTypes[i] = NUM2INT(param_type);

		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = PQsendQueryParams(conn, StringValuePtr(command), nParams, paramTypes, 
		(const char * const *)paramValues, paramLengths, paramFormats, resultFormat);

	rb_gc_unregister_address(&gc_array);	

	xfree(paramTypes);
	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

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

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

Execute prepared named statement specified by statement_name asynchronously, and returns immediately. On failure, it raises a PGError exception.

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 => Fixnum (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.



1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
# File 'ext/pg.c', line 1752

static VALUE
pgconn_send_query_prepared(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = get_pgconn(self);
	int result;
	VALUE name, params, in_res_fmt;
	VALUE param, param_value, param_format;
	VALUE param_value_tmp;
	VALUE sym_value, sym_format;
	VALUE gc_array;
	VALUE error;
	int i = 0;
	int nParams;
	char ** paramValues;
	int *paramLengths;
	int *paramFormats;
	int resultFormat;

	rb_scan_args(argc, argv, "12", &name, &params, &in_res_fmt);
	Check_Type(name, T_STRING);

	if(NIL_P(params)) {
		params = rb_ary_new2(0);
		resultFormat = 0;
	}
	else {
		Check_Type(params, T_ARRAY);
	}

	if(NIL_P(in_res_fmt)) {
		resultFormat = 0;
	}
	else {
		resultFormat = NUM2INT(in_res_fmt);
	}

	gc_array = rb_ary_new();
	rb_gc_register_address(&gc_array);
	sym_value = ID2SYM(rb_intern("value"));
	sym_format = ID2SYM(rb_intern("format"));
	nParams = RARRAY_LEN(params);
	paramValues = ALLOC_N(char *, nParams);
	paramLengths = ALLOC_N(int, nParams);
	paramFormats = ALLOC_N(int, nParams);
	for(i = 0; i < nParams; i++) {
		param = rb_ary_entry(params, i);
		if (TYPE(param) == T_HASH) {
			param_value_tmp = rb_hash_aref(param, sym_value);
			if(param_value_tmp == Qnil)
				param_value = param_value_tmp;
			else
				param_value = rb_obj_as_string(param_value_tmp);
			param_format = rb_hash_aref(param, sym_format);
		}
		else {
			if(param == Qnil)
				param_value = param;
			else
				param_value = rb_obj_as_string(param);
			param_format = INT2NUM(0);
		}

		if(param_value == Qnil) {
			paramValues[i] = NULL;
			paramLengths[i] = 0;
		}
		else {
			Check_Type(param_value, T_STRING);
			/* make sure param_value doesn't get freed by the GC */
			rb_ary_push(gc_array, param_value);
			paramValues[i] = StringValuePtr(param_value);
			paramLengths[i] = RSTRING_LEN(param_value);
		}

		if(param_format == Qnil)
			paramFormats[i] = 0;
		else
			paramFormats[i] = NUM2INT(param_format);
	}

	result = PQsendQueryPrepared(conn, StringValuePtr(name), nParams, 
		(const char * const *)paramValues, paramLengths, paramFormats, 
		resultFormat);

	rb_gc_unregister_address(&gc_array);

	xfree(paramValues);
	xfree(paramLengths);
	xfree(paramFormats);

	if(result == 0) {
		error = rb_exc_new2(rb_ePGError, 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)


879
880
881
882
883
# File 'ext/pg.c', line 879

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

#set_client_encoding(encoding) ⇒ Object

Sets the client encoding to the encoding String.



2479
2480
2481
2482
2483
2484
2485
2486
2487
# File 'ext/pg.c', line 2479

static VALUE
pgconn_set_client_encoding(VALUE self, VALUE str)
{
	Check_Type(str, T_STRING);
	if ((PQsetClientEncoding(get_pgconn(self), StringValuePtr(str))) == -1){
		rb_raise(rb_ePGError, "invalid encoding name: %s",StringValuePtr(str));
	}
	return Qnil;
}

#set_error_verbosity(verbosity) ⇒ Fixnum

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

  • PQERRORS_TERSE

  • PQERRORS_DEFAULT

  • PQERRORS_VERBOSE

Returns:

  • (Fixnum)


2300
2301
2302
2303
2304
2305
2306
# File 'ext/pg.c', line 2300

static VALUE
pgconn_set_error_verbosity(VALUE self, VALUE in_verbosity)
{
	PGconn *conn = get_pgconn(self);
	PGVerbosity verbosity = NUM2INT(in_verbosity);
	return INT2FIX(PQsetErrorVerbosity(conn, verbosity));
}

#set_notice_processor {|message| ... } ⇒ 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.

This function takes a new block to act as the handler, which should accept a single parameter that will be a PGresult 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.

Yields:

  • (message)

Returns:

  • (Proc)


2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
# File 'ext/pg.c', line 2433

static VALUE
pgconn_set_notice_processor(VALUE self)
{
	VALUE proc, old_proc;
	PGconn *conn = get_pgconn(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(conn, NULL, NULL);

	old_proc = rb_iv_get(self, "@notice_processor");
	if( rb_block_given_p() ) {
		proc = rb_block_proc();
		PQsetNoticeProcessor(conn, notice_processor_proxy, (void *)self);
	} else {
		/* if no block is given, set back to default */
		proc = Qnil;
		PQsetNoticeProcessor(conn, default_notice_processor, NULL);
	}

	rb_iv_set(self, "@notice_processor", 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.

This function takes a new block to act as the handler, which should accept a single parameter that will be a PGresult 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.

Yields:

  • (result)

Returns:

  • (Proc)


2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
# File 'ext/pg.c', line 2387

static VALUE
pgconn_set_notice_receiver(VALUE self)
{
	VALUE proc, old_proc;
	PGconn *conn = get_pgconn(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(conn, NULL, NULL);

	old_proc = rb_iv_get(self, "@notice_receiver");
	if( rb_block_given_p() ) {
		proc = rb_block_proc();
		PQsetNoticeReceiver(conn, notice_receiver_proxy, (void *)self);
	} else {
		/* if no block is given, set back to default */
		proc = Qnil;
		PQsetNoticeReceiver(conn, default_notice_receiver, NULL);
	}

	rb_iv_set(self, "@notice_receiver", proc);
	return old_proc;
}

#setnonblocking(Boolean) ⇒ nil

Sets the nonblocking status of the connection. In the blocking state, calls to PGconn#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 PGconn#send_query will return an error if the socket is not ready for writing. Note: This function does not affect PGconn#exec, because that function doesn’t return until the server has processed the query and returned the results. Returns nil.

Returns:

  • (nil)


1981
1982
1983
# File 'ext/pg.c', line 1981

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

#socketFixnum

Returns the socket’s file descriptor for this connection.

Returns:

  • (Fixnum)


905
906
907
908
909
910
911
912
# File 'ext/pg.c', line 905

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

#statusObject

Returns status of connection : CONNECTION_OK or CONNECTION_BAD



802
803
804
805
806
# File 'ext/pg.c', line 802

static VALUE
pgconn_status(VALUE self)
{
	return INT2NUM(PQstatus(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)


2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
# File 'ext/pg.c', line 2317

static VALUE
pgconn_trace(VALUE self, VALUE stream)
{
	VALUE fileno;
	FILE *new_fp;
	int old_fd, new_fd;
	VALUE new_file;

	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));
	rb_iv_set(self, "@trace_stream", new_file);

	PQtrace(get_pgconn(self), new_fp);
	return Qnil;
}

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

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)

Returns:

  • (nil)


2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
# File 'ext/pg.c', line 2497

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

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

	}
	else {
		/* no block supplied? */
		rb_raise(rb_eArgError, "Must supply block for PGconn#transaction");
	}
	return Qnil;
}

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


819
820
821
822
823
# File 'ext/pg.c', line 819

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

#ttyObject

Returns the connected pgtty. (Obsolete)



774
775
776
777
778
779
780
# File 'ext/pg.c', line 774

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

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



1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
# File 'ext/pg.c', line 1501

static VALUE
pgconn_s_unescape_bytea(VALUE self, VALUE str)
{
	unsigned char *from, *to;
	size_t to_len;
	VALUE ret;

	Check_Type(str, T_STRING);
	from = (unsigned char*)StringValuePtr(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)


2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
# File 'ext/pg.c', line 2358

static VALUE
pgconn_untrace(VALUE self)
{
	VALUE trace_stream;
	PQuntrace(get_pgconn(self));
	trace_stream = rb_iv_get(self, "@trace_stream");
	rb_funcall(trace_stream, rb_intern("close"), 0);
	rb_iv_set(self, "@trace_stream", Qnil);
	return Qnil;
}

#userObject

Returns the authenticated user name.



719
720
721
722
723
724
725
# File 'ext/pg.c', line 719

static VALUE
pgconn_user(VALUE self)
{
	char *user = PQuser(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 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.

Overloads:

  • #wait_for_notify([ timeout ]) ⇒ String

    Returns:

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

    Yields:

    • (event, pid)


2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
# File 'ext/pg.c', line 2130

static VALUE
pgconn_wait_for_notify(int argc, VALUE *argv, VALUE self)
{
	PGconn *conn = get_pgconn( self );
	PGnotify *notification;
	int sd = PQsocket( conn );
	int ret;
	struct timeval timeout;
	struct timeval *ptimeout = NULL;
	VALUE timeout_in, relname = Qnil, be_pid = Qnil;
	double timeout_sec;
	fd_set sd_rset;

	if ( sd < 0 )
		rb_bug("PQsocket(conn): couldn't fetch the connection's socket!");

	if ( rb_scan_args(argc, argv, "01", &timeout_in) == 1 ) {
		timeout_sec = NUM2DBL( timeout_in );
		timeout.tv_sec = (long)timeout_sec;
		timeout.tv_usec = (long)( (timeout_sec - (long)timeout_sec) * 1e6 );
		ptimeout = &timeout;
	}

	/* Check for notifications */
	while ( (notification = PQnotifies(conn)) == NULL ) {
		FD_ZERO( &sd_rset );
		FD_SET( sd, &sd_rset );

		/* Wait for the socket to become readable before checking again */
		if ( (ret = rb_thread_select(sd+1, &sd_rset, NULL, NULL, ptimeout)) < 0 )
			rb_sys_fail( 0 );

		/* Return nil if the select timed out */
		if ( ret == 0 ) return Qnil;

		/* Read the socket */
		if ( (ret = PQconsumeInput(conn)) != 1 )
			rb_raise(rb_ePGError, "PQconsumeInput == %d: %s", ret, PQerrorMessage(conn));
	}

	relname = rb_tainted_str_new2( notification->relname );
	be_pid = INT2NUM( notification->be_pid );
	PQfreemem( notification );

	if ( rb_block_given_p() )
		rb_yield_splat( rb_ary_new3(2, relname, be_pid) );

	return relname;
}