Class: PGconn

Class | PGconn
In: | ext/pg.c
Parent: | Object

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.

### Methods

async_exec async_query backend_pid block cancel close conndefaults conndefaults connect_poll connect_start connection_needs_password connection_used_password consume_input db describe_portal describe_prepared encrypt_password error_message escape escape_bytea escape_bytea escape_string escape_string exec exec_prepared finish flush get_client_encoding get_copy_data get_last_result get_result host is_busy isnonblocking isthreadsafe lo_close lo_creat lo_create lo_export lo_import lo_lseek lo_open lo_read lo_seek lo_tell lo_truncate lo_unlink lo_write loclose locreat locreate loexport loimport lolseek loopen loread loseek lotell lotruncate lounlink lowrite make_empty_pgresult new notifies options parameter_status pass port prepare protocol_version put_copy_data put_copy_end query quote_ident quote_ident reset reset_poll reset_start send_describe_portal send_describe_prepared send_prepare send_query send_query_prepared server_version set_client_encoding set_error_verbosity set_notice_processor set_notice_receiver setnonblocking socket status trace transaction transaction_status tty unescape_bytea unescape_bytea untrace user

### Constants

CONNECTION_OK | = | PGconn CLASS CONSTANTS |  | Connection Status
CONNECTION_BAD | = | INT2FIX(CONNECTION_BAD)
CONNECTION_STARTED | = | PGconn CLASS CONSTANTS |  | Nonblocking connection status
CONNECTION_MADE | = | INT2FIX(CONNECTION_MADE)
CONNECTION_AWAITING_RESPONSE | = | INT2FIX(CONNECTION_AWAITING_RESPONSE)
CONNECTION_AUTH_OK | = | INT2FIX(CONNECTION_AUTH_OK)
CONNECTION_SSL_STARTUP | = | INT2FIX(CONNECTION_SSL_STARTUP)
CONNECTION_SETENV | = | INT2FIX(CONNECTION_SETENV)
PGRES_POLLING_READING | = | PGconn CLASS CONSTANTS |  | Nonblocking connection polling status
PGRES_POLLING_WRITING | = | INT2FIX(PGRES_POLLING_WRITING)
PGRES_POLLING_FAILED | = | INT2FIX(PGRES_POLLING_FAILED)
PGRES_POLLING_OK | = | INT2FIX(PGRES_POLLING_OK)
PQTRANS_IDLE | = | PGconn CLASS CONSTANTS |  | Transaction Status
PQTRANS_ACTIVE | = | INT2FIX(PQTRANS_ACTIVE)
PQTRANS_INTRANS | = | INT2FIX(PQTRANS_INTRANS)
PQTRANS_INERROR | = | INT2FIX(PQTRANS_INERROR)
PQTRANS_UNKNOWN | = | INT2FIX(PQTRANS_UNKNOWN)
PQERRORS_TERSE | = | PGconn CLASS CONSTANTS |  | Error Verbosity
PQERRORS_DEFAULT | = | INT2FIX(PQERRORS_DEFAULT)
PQERRORS_VERBOSE | = | INT2FIX(PQERRORS_VERBOSE)
INV_WRITE | = | PGconn CLASS CONSTANTS |  | Large Objects
INV_READ | = | INT2FIX(INV_READ)
SEEK_SET | = | INT2FIX(SEEK_SET)
SEEK_CUR | = | INT2FIX(SEEK_CUR)
SEEK_END | = | INT2FIX(SEEK_END)

### Public Class methods

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

PGconn.connect_start(connection_hash) → PGconn
PGconn.connect_start(connection_string) → PGconn
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.

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

conn.escape_bytea( string ) → String
PGconn.escape_bytea( string ) → String # DEPRECATED

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.

conn.escape_string( str ) → String
PGconn.escape_string( str ) → String # DEPRECATED

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.

PGconn.isthreadsafe() → Boolean

Returns `true` if libpq is thread safe, `false` otherwise.

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

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

connection_hash example: +PGconn.connect(:dbname=>’test’, :port=>5432) connection_string example: +PGconn.connect("dbname=test port=5432") connection_hash example: +PGconn.connect(nil,5432,nil,nil,’test’,nil,nil)

     On failure, it raises a PGError exception.

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

PGconn.unescape_bytea( string )

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.

### Public Instance methods

conn.async_exec(sql [, params, result_format ] ) → PGresult

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.

async_query(...)

Alias for async_exec

conn.backend_pid() → Fixnum

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

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

conn.cancel() → String

Requests cancellation of the command currently being processed.

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

close()

Alias for finish

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

conn.connect_poll() → Fixnum

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.

conn.connection_needs_password() → Boolean

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

conn.connection_used_password() → Boolean

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

conn.consume_input()

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.

conn.db()

Returns the connected database name.

conn.describe_portal( portal_name ) → PGresult

Retrieve information about the portal portal_name.

conn.describe_prepared( statement_name ) → PGresult

Retrieve information about the prepared statement statement_name.

conn.error() → String

Returns the error message about connection.

escape(p1)

Alias for escape_string

conn.escape_bytea( string ) → String
PGconn.escape_bytea( string ) → String # DEPRECATED

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.

conn.escape_string( str ) → String
PGconn.escape_string( str ) → String # DEPRECATED

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.

conn.exec(sql [, params, result_format ] ) → PGresult

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.

conn.exec_prepared(statement_name [, params, result_format ] ) → PGresult

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.

conn.finish()

Closes the backend connection.

conn.flush() → Boolean

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.

conn.get_client_encoding() → String

Returns the client encoding as a String.

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

conn.get_last_result( ) → PGresult

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.

conn.get_result() → PGresult

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.

conn.host()

Returns the connected server name.

conn.is_busy() → Boolean

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

conn.isnonblocking() → Boolean

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

conn.lo_close( lo_desc ) → nil

Closes the postgres large object of lo_desc.

conn.lo_creat( [mode] ) → Fixnum

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

conn.lo_create( oid ) → Fixnum

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

conn.lo_export( oid, file ) → nil

Saves a large object of oid to a file.

conn.lo_import(file) → Fixnum

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

On failure, it raises a PGError exception.

lo_lseek(p1, p2, p3)

call-seq

       conn.lo_lseek( lo_desc, offset, whence ) -> Fixnum

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

conn.lo_open( oid, [mode] ) → Fixnum

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

conn.lo_read( lo_desc, len ) → String

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

lo_seek(p1, p2, p3)

Alias for lo_lseek

conn.lo_tell( lo_desc ) → Fixnum

Returns the current position of the large object lo_desc.

conn.lo_truncate( lo_desc, len ) → nil

Truncates the large object lo_desc to size len.

conn.lo_unlink( oid ) → nil

Unlinks (deletes) the postgres large object of oid.

conn.lo_write( lo_desc, buffer ) → Fixnum

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

loclose(p1)

Alias for lo_close

locreat(...)

Alias for lo_creat

locreate(p1)

Alias for lo_create

loexport(p1, p2)

Alias for lo_export

loimport(p1)

Alias for lo_import

lolseek(p1, p2, p3)

Alias for lo_lseek

loopen(...)

Alias for lo_open

loread(p1, p2)

Alias for lo_read

loseek(p1, p2, p3)

Alias for lo_lseek

lotell(p1)

Alias for lo_tell

lotruncate(p1, p2)

Alias for lo_truncate

lounlink(p1)

Alias for lo_unlink

lowrite(p1, p2)

Alias for lo_write

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

conn.notifies()

Returns an array of the unprocessed notifiers. If there is no unprocessed notifier, it returns `nil`.

conn.options()

Returns backend option string.

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

conn.pass()

Returns the authenticated user name.

conn.port()

Returns the connected server port number.

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

conn.protocol_version → Integer

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

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

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

query(...)

Alias for exec

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

conn.reset()

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

conn.reset_poll → Fixnum

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

conn.reset_start() → nil

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.

conn.send_describe_portal( portal_name ) → nil

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

conn.send_describe_prepared( statement_name ) → nil

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

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

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

conn.send_query_prepared( statement_name [, params, result_format ] )
→ nil

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.

conn.server_version → Integer

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.

conn.set_client_encoding( encoding )

Sets the client encoding to the encoding String.

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

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

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

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

conn.socket() → Fixnum

Returns the socket‘s file descriptor for this connection.

conn.status()

Returns status of connection : CONNECTION_OK or CONNECTION_BAD

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

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

conn.transaction_status()

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)

conn.tty()

Returns the connected pgtty. (Obsolete)

PGconn.unescape_bytea( string )

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.

conn.untrace() → nil

Disables the message tracing.

conn.user()

Returns the authenticated user name.

[Validate]