PG::
Connection class
| Superclass | rb_cObject |
| Included Modules |
The PostgreSQL connection class. The interface for this class is based on libpq, the C application programmer’s interface to PostgreSQL. Some familiarity with libpq is recommended, but not necessary.
For example, to send query to the database on the localhost:
require 'pg' conn = PG::Connection.open(:dbname => 'test') res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil]) # Equivalent to: # res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
See the PG::Result class for information on working with the results of a query.
Many methods of this class have three variants kind of:
-
exec- the base method which is an alias toasync_exec. This is the method that should be used in general. -
async_exec- the async aware version of the method, implemented by libpq’s async API. -
sync_exec- the method version that is implemented by blocking function(s) of libpq.
Sync and async version of the method can be switched by Connection.async_api= , however it is not recommended to change the default.
Public Class Methods
Switch between sync and async libpq API.
PG::Connection.async_api = true
this is the default. It sets an alias from exec to async_exec, reset to async_reset and so on.
PG::Connection.async_api = false
sets an alias from exec to sync_exec, reset to sync_reset and so on.
pg-1.1.0+ defaults to libpq’s async API for query related blocking methods. pg-1.3.0+ defaults to libpq’s async API for all possibly blocking methods.
PLEASE NOTE: This method is not part of the public API and is for debug and development use only. Do not use this method in production code. Any issues with the default setting of async_api=true should be reported to the maintainers instead.
PG::Connection.new(connection_hash) → conn
PG::Connection.new(connection_string) → conn
PG::Connection.new(host, port, options, tty, dbname, user, password) → conn
PG::Connection.ping(connection_string) → Integer
PG::Connection.ping(host, port, options, tty, dbname, login, password) → Integer
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
Return the Postgres connection defaults structure as a Hash keyed by option keyword (as a Symbol).
See also conndefaults
PG::Connection.new(connection_hash) → conn
PG::Connection.new(connection_string) → conn
PG::Connection.new(host, port, options, tty, dbname, user, password) → conn
Convert Hash options to connection String
Values are properly quoted and escaped.
PG::Connection.connect_start(connection_string) → conn
PG::Connection.connect_start(host, port, options, tty, dbname, login, password) → conn
This is an asynchronous version of PG::Connection.new.
Use connect_poll to poll the status of the connection.
NOTE: this does not set the connection’s client_encoding for you if Encoding.default_internal is set. To set it after the connection is established, call internal_encoding=. You can also set it automatically by setting ENV['PGCLIENTENCODING'], or include the ‘options’ connection parameter.
See also the ‘sample’ directory of this gem and the corresponding libpq functions.
Returns parsed connection options from the provided connection string as an array of hashes. Each hash has the same keys as PG::Connection.conndefaults() . The values from the conninfo_string are stored in the :val key.
This is an older, deprecated version of encrypt_password. The difference is that this function always uses md5 as the encryption algorithm.
Escapes binary data for use within an SQL command with the type bytea.
Certain byte values must be escaped (but all byte values may be escaped) when used as part of a bytea literal in an SQL statement. In general, to escape a byte, it is converted into the three digit octal number equal to the octet value, and preceded by two backslashes. The single quote (‘) and backslash () characters have special alternative escape sequences. escape_bytea performs this operation, escaping only the minimally required bytes.
Consider using exec_params, which avoids the need for passing values inside of SQL commands.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
Returns a SQL-safe version of the String str. This is the preferred way to make strings safe for inclusion in SQL queries.
Consider using exec_params, which avoids the need for passing values inside of SQL commands.
Character encoding of escaped string will be equal to client encoding of connection.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
See also convenience functions escape_literal and escape_identifier which also add proper quotes around the string.
PG::Connection.new(connection_hash) → conn
PG::Connection.new(connection_string) → conn
PG::Connection.new(host, port, options, tty, dbname, user, password) → conn
Create a connection to the specified server.
connection_hash must be a ruby Hash with connection parameters. See the list of valid parameters in the PostgreSQL documentation.
There are two accepted formats for connection_string: plain keyword = value strings and URIs. See the documentation of connection strings.
The positional parameter form has the same functionality except that the missing parameters will always take on default values. The parameters are:
host
server hostname
port
server port number
options
backend options
tty
(ignored in all versions of PostgreSQL)
dbname
connecting database name
user
login user name
password
login password
If the Ruby default internal encoding is set (i.e., Encoding.default_internal != nil), the connection will have its client_encoding set accordingly.
Raises a PG::Error if the connection fails.
Examples:
# Connect using all defaults PG::Connection.new # As a Hash PG::Connection.new( dbname: 'test', port: 5432 ) # As a String PG::Connection.new( "dbname=test port=5432" ) # As an Array PG::Connection.new( nil, 5432, nil, nil, 'test', nil, nil ) # As an URI PG::Connection.new( "postgresql://user:pass@pgsql.example.com:5432/testdb?sslmode=require" )
Specifying Multiple Hosts
It is possible to specify multiple hosts to connect to, so that they are tried in the given order or optionally in random order. In the Keyword/Value format, the host, hostaddr, and port options accept comma-separated lists of values. The details to libpq describe how it works, but there are two small differences how ruby-pg handles multiple hosts:
-
All hosts are resolved before the first connection is tried. This means that when
load_balance_hostsis set torandom, then all resolved addresses are tried randomly in one level. When a host resolves to more than one address, it is therefore tried more often than a host that has only one address. -
When a timeout occurs due to the value of
connect_timeout, then the givenhost,hostaddrandportcombination is not tried a second time, even if it’s specified several times. It’s still possible to do load balancing withload_balance_hostsset torandomand to increase the number of connections a node gets, when the hostname is provided multiple times in the host string. This is because in non-timeout cases the host is tried multiple times.
PG::Connection.new(connection_hash) → conn
PG::Connection.new(connection_string) → conn
PG::Connection.new(host, port, options, tty, dbname, user, password) → conn
Parse the connection args into a connection-parameter string. See PG::Connection.new for valid arguments.
It accepts:
-
an option String kind of “host=name port=5432”
-
an option Hash kind of {host: “name”, port: 5432}
-
URI string
-
URI object
-
positional arguments
The method adds the option “fallback_application_name” if it isn’t already set. It returns a connection string with “key=value” pairs.
PG::Connection.ping(connection_string) → Integer
PG::Connection.ping(host, port, options, tty, dbname, login, password) → Integer
PQpingParams reports the status of the server.
It accepts connection parameters identical to those of PQ::Connection.new . It is not necessary to supply correct user name, password, or database name values to obtain the server status; however, if incorrect values are provided, the server will log a failed connection attempt.
See PG::Connection.new for a description of the parameters.
Returns one of:
PQPING_OK
server is accepting connections
PQPING_REJECT
server is alive but rejecting connections
PQPING_NO_RESPONSE
could not establish connection
PQPING_NO_ATTEMPT
connection not attempted (bad params)
See also check_socket for a way to check the connection without doing any server communication.
Quote a single value for use in a connection-parameter string.
quote_ident( array ) → String
PG::Connection.quote_ident( str ) → String
PG::Connection.quote_ident( array ) → String
Returns a string that is safe for inclusion in a SQL query as an identifier. Note: this is not a quote function for values, but for identifiers.
For example, in a typical SQL query: SELECT FOO FROM MYTABLE The identifier FOO is folded to lower case, so it actually means foo. If you really want to access the case-sensitive field name FOO, use this function like conn.quote_ident('FOO'), which will return "FOO" (with double-quotes). PostgreSQL will see the double-quotes, and it will not fold to lower case.
Similarly, this function also protects against special characters, and other things that might allow SQL injection if the identifier comes from an untrusted source.
If the parameter is an Array, then all it’s values are separately quoted and then joined by a “.” character. This can be used for identifiers in the form “schema”.“table”.“column” .
This method is functional identical to the encoder PG::TextEncoder::Identifier .
If the instance method form is used and the input string character encoding is different to the connection encoding, then the string is converted to this encoding, so that the returned string is always encoded as PG::Connection#internal_encoding .
In the singleton form (PG::Connection.quote_ident) the character encoding of the result string is set to the character encoding of the input string.
PG::Connection.new(connection_hash) → conn
PG::Connection.new(connection_string) → conn
PG::Connection.new(host, port, options, tty, dbname, user, password) → conn
PG::Connection.new(connection_hash) → conn
PG::Connection.new(connection_string) → conn
PG::Connection.new(host, port, options, tty, dbname, user, password) → conn
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
Submits a request to close the specified portal, and waits for completion.
close_portal allows an application to trigger a close of a previously created portal. Closing a portal releases all of its associated resources on the server and allows its name to be reused. (pg does not provide any direct access to portals, but you can use this function to close a cursor created with a DECLARE CURSOR SQL command.)
portal_name can be “” or nil to reference the unnamed portal. It is fine if no portal exists with this name, in that case the operation is a no-op. On success, a PG::Result with status PGRES_COMMAND_OK is returned.
See also corresponding libpq function.
Available since PostgreSQL-17.
Submits a request to close the specified prepared statement, and waits for completion. close_prepared allows an application to close a previously prepared statement. Closing a statement releases all of its associated resources on the server and allows its name to be reused. It’s the same as using the DEALLOCATE SQL statement, but on a lower protocol level.
statement_name can be “” or nil to reference the unnamed statement. It is fine if no statement exists with this name, in that case the operation is a no-op. On success, a PG::Result with status PGRES_COMMAND_OK is returned.
See also corresponding libpq function.
Available since PostgreSQL-17.
Retrieve information about the portal portal_name.
See also corresponding libpq function.
Retrieve information about the prepared statement statement_name.
See also corresponding libpq function.
Sends SQL query request specified by sql to PostgreSQL. On success, it returns a PG::Result instance with all result rows and columns. On failure, it raises a PG::Error.
For backward compatibility, if you pass more than one parameter to this method, it will call exec_params for you. New code should explicitly use exec_params if argument placeholders are used.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
exec is an alias for async_exec which is almost identical to sync_exec . sync_exec is implemented on the simpler synchronous command processing API of libpq, whereas async_exec is implemented on the asynchronous API and on ruby’s IO mechanisms. Only async_exec is compatible to Fiber.scheduler based asynchronous IO processing introduced in ruby-3.0. Both methods ensure that other threads can process while waiting for the server to complete the request, but sync_exec blocks all signals to be processed until the query is finished. This is most notably visible by a delayed reaction to Control+C. It’s not recommended to use explicit sync or async variants but exec instead, unless you have a good reason to do so.
See also corresponding libpq function.
Sends SQL query request specified by sql to PostgreSQL using placeholders for parameters.
Returns a PG::Result instance on success. On failure, it raises a PG::Error.
params is an array of the bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form:
{:value => String (value of bind parameter)
:type => Integer (oid of type of bind parameter)
:format => Integer (0 for text, 1 for binary)
}
or, it may be a String. If it is a string, that is equivalent to the hash:
{ :value => <string value>, :type => 0, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
The optional result_format should be 0 for text results, 1 for binary.
type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
The primary advantage of exec_params over exec is that parameter values can be separated from the command string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike exec, exec_params allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) This is a limitation of the underlying protocol, but has some usefulness as an extra defense against SQL-injection attacks.
See also corresponding libpq function.
Execute prepared named statement specified by statement_name. Returns a PG::Result instance on success. On failure, it raises a PG::Error.
params is an array of the optional bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form:
{:value => String (value of bind parameter)
:format => Integer (0 for text, 1 for binary)
}
or, it may be a String. If it is a string, that is equivalent to the hash:
{ :value => <string value>, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
The optional result_format should be 0 for text results, 1 for binary.
type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec_prepared returns the value of the block.
See also corresponding libpq function.
Attempts to flush any queued output data to the server. Returns true if data is successfully flushed, false if not. It can only return false if connection is in nonblocking mode. Raises PG::Error if some other failure occurred.
This function retrieves all available results on the current connection (from previously issued asynchronous commands like +send_query()+) and returns the last non-NULL result, or nil if no results are available.
If the last result contains a bad result_status, an appropriate exception is raised.
This function is similar to get_result except that it is designed to get one and only one result and that it checks the result state.
Prepares statement sql with name name to be executed later. Returns a PG::Result instance on success. On failure, it raises a PG::Error.
param_types is an optional parameter to specify the Oids of the types of the parameters.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query.
See also corresponding libpq function.
Sends SQL query request specified by sql to PostgreSQL. On success, it returns a PG::Result instance with all result rows and columns. On failure, it raises a PG::Error.
For backward compatibility, if you pass more than one parameter to this method, it will call exec_params for you. New code should explicitly use exec_params if argument placeholders are used.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
exec is an alias for async_exec which is almost identical to sync_exec . sync_exec is implemented on the simpler synchronous command processing API of libpq, whereas async_exec is implemented on the asynchronous API and on ruby’s IO mechanisms. Only async_exec is compatible to Fiber.scheduler based asynchronous IO processing introduced in ruby-3.0. Both methods ensure that other threads can process while waiting for the server to complete the request, but sync_exec blocks all signals to be processed until the query is finished. This is most notably visible by a delayed reaction to Control+C. It’s not recommended to use explicit sync or async variants but exec instead, unless you have a good reason to do so.
See also corresponding libpq function.
Sets the client encoding to the encoding String.
Returns the key of the backend server process for this connection. This key can be used to cancel queries on the server.
Returns the process ID of the backend server process for this connection. Note that this is a PID on database server host.
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.
Requests cancellation of the command currently being processed.
Returns nil on success, or a string containing the error message if a failure occurs.
On PostgreSQL-17+ client libaray the class PG::CancelConnection is used. On older client library a pure ruby implementation is used.
Read all pending socket input to internal memory and raise an exception in case of errors.
This verifies that the connection socket is in a usable state and not aborted in any way. No communication is done with the server. Only pending data is read from the socket - the method doesn’t wait for any outstanding server answers.
Raises a kind of PG::Error if there was an error reading the data or if the socket is in a failure state.
The method doesn’t verify that the server is still responding. To verify that the communication to the server works, it is recommended to use something like conn.exec('') instead.
Sets the client encoding to the encoding String.
Submits a request to close the specified portal, and waits for completion.
close_portal allows an application to trigger a close of a previously created portal. Closing a portal releases all of its associated resources on the server and allows its name to be reused. (pg does not provide any direct access to portals, but you can use this function to close a cursor created with a DECLARE CURSOR SQL command.)
portal_name can be “” or nil to reference the unnamed portal. It is fine if no portal exists with this name, in that case the operation is a no-op. On success, a PG::Result with status PGRES_COMMAND_OK is returned.
See also corresponding libpq function.
Available since PostgreSQL-17.
Submits a request to close the specified prepared statement, and waits for completion. close_prepared allows an application to close a previously prepared statement. Closing a statement releases all of its associated resources on the server and allows its name to be reused. It’s the same as using the DEALLOCATE SQL statement, but on a lower protocol level.
statement_name can be “” or nil to reference the unnamed statement. It is fine if no statement exists with this name, in that case the operation is a no-op. On success, a PG::Result with status PGRES_COMMAND_OK is returned.
See also corresponding libpq function.
Available since PostgreSQL-17.
Returns an array of Hashes with connection defaults. See ::conndefaults for details.
Returns a Hash with connection defaults. See ::conndefaults_hash for details.
Returns one of:
PGRES_POLLING_READING
wait until the socket is ready to read
PGRES_POLLING_WRITING
wait until the socket is ready to write
PGRES_POLLING_FAILED
the asynchronous connection has failed
PGRES_POLLING_OK
the asynchronous connection is ready
Example:
require "io/wait" conn = PG::Connection.connect_start(dbname: 'mydatabase') status = conn.connect_poll while(status != PG::PGRES_POLLING_OK) do # do some work while waiting for the connection to complete if(status == PG::PGRES_POLLING_READING) unless conn.socket_io.wait_readable(10.0) raise "Asynchronous connection timed out!" end elsif(status == PG::PGRES_POLLING_WRITING) unless conn.socket_io.wait_writable(10.0) raise "Asynchronous connection timed out!" end end status = conn.connect_poll end # now conn.status == CONNECTION_OK, and connection # is ready.
Returns true if the authentication method required a password, but none was available. false otherwise.
Returns true if the authentication method used a caller-supplied password, false otherwise.
Returns the connection options used by a live connection.
Return the Postgres connection info structure as a Hash keyed by option keyword (as a Symbol).
See also conninfo
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.
Execute a copy process for transferring data to or from the server.
This issues the SQL COPY command via exec. The response to this (if there is no error in the command) is a PG::Result object that is passed to the block, bearing a status code of PGRES_COPY_OUT or PGRES_COPY_IN (depending on the specified copy direction). The application should then use put_copy_data or get_copy_data to receive or transmit data rows and should return from the block when finished.
copy_data returns another PG::Result object when the data transfer is complete. An exception is raised if some problem was encountered, so it isn’t required to make use of any of them. At this point further SQL commands can be issued via exec. (It is not possible to execute other SQL commands using the same connection while the COPY operation is in progress.)
This method ensures, that the copy process is properly terminated in case of client side or server side failures. Therefore, in case of blocking mode of operation, copy_data is preferred to raw calls of put_copy_data, get_copy_data and put_copy_end.
coder can be a PG::Coder derivation (typically PG::TextEncoder::CopyRow or PG::TextDecoder::CopyRow). This enables encoding of data fields given to put_copy_data or decoding of fields received by get_copy_data.
Example with CSV input format:
conn.exec "create table my_table (a text,b text,c text,d text)" conn.copy_data "COPY my_table FROM STDIN CSV" do conn.put_copy_data "some,data,to,copy\n" conn.put_copy_data "more,data,to,copy\n" end
This creates my_table and inserts two CSV rows.
The same with text format encoder PG::TextEncoder::CopyRow and Array input:
enco = PG::TextEncoder::CopyRow.new conn.copy_data "COPY my_table FROM STDIN", enco do conn.put_copy_data ['some', 'data', 'to', 'copy'] conn.put_copy_data ['more', 'data', 'to', 'copy'] end
All 4 CopyRow classes can take a type map to specify how the columns are mapped to and from the database format. For details see the particular CopyRow class description.
PG::BinaryEncoder::CopyRow can be used to send data in binary format to the server. In this case copy_data generates the header and trailer data automatically:
enco = PG::BinaryEncoder::CopyRow.new conn.copy_data "COPY my_table FROM STDIN (FORMAT binary)", enco do conn.put_copy_data ['some', 'data', 'to', 'copy'] conn.put_copy_data ['more', 'data', 'to', 'copy'] end
Example with CSV output format:
conn.copy_data "COPY my_table TO STDOUT CSV" do while row=conn.get_copy_data p row end end
This prints all rows of my_table to stdout:
"some,data,to,copy\n" "more,data,to,copy\n"
The same with text format decoder PG::TextDecoder::CopyRow and Array output:
deco = PG::TextDecoder::CopyRow.new conn.copy_data "COPY my_table TO STDOUT", deco do while row=conn.get_copy_data p row end end
This receives all rows of my_table as ruby array:
["some", "data", "to", "copy"] ["more", "data", "to", "copy"]
Also PG::BinaryDecoder::CopyRow can be used to retrieve data in binary format from the server. In this case the header and trailer data is processed by the decoder and the remaining nil from get_copy_data is processed by copy_data, so that binary data can be processed equally to text data:
deco = PG::BinaryDecoder::CopyRow.new conn.copy_data "COPY my_table TO STDOUT (FORMAT binary)", deco do while row=conn.get_copy_data p row end end
This receives all rows of my_table as ruby array:
["some", "data", "to", "copy"] ["more", "data", "to", "copy"]
Returns the connected database name.
Returns the default coder object that is currently set for type casting of received data by get_copy_data .
Returns either:
-
a kind of
PG::Coder -
nil- type encoding is disabled, returned data will be a String.
Set the default coder that is used for type casting of received data by get_copy_data .
decoder can be:
-
a kind of
PG::Coder -
nil- disable type decoding, returned data will be a String.
Retrieve information about the portal portal_name.
See also corresponding libpq function.
Retrieve information about the prepared statement statement_name.
See also corresponding libpq function.
Silently discard any prior query result that application didn’t eat. This is internally used prior to Connection#exec and sibling methods. It doesn’t raise an exception on connection errors, but returns false instead.
Returns:
-
nilwhen the connection is already idle -
truewhen some results have been discarded -
falsewhen a failure occurred and the connection was closed
Returns the default coder object that is currently set for type casting of parameters to put_copy_data .
Returns either:
-
a kind of
PG::Coder -
nil- type encoding is disabled, data must be a String.
Set the default coder that is used for type casting of parameters to put_copy_data .
encoder can be:
-
a kind of
PG::Coder -
nil- disable type encoding, data must be a String.
This function is intended to be used by client applications that wish to send commands like ALTER USER joe PASSWORD 'pwd'. It is good practice not to send the original cleartext password in such a command, because it might be exposed in command logs, activity displays, and so on. Instead, use this function to convert the password to encrypted form before it is sent.
The password and username arguments are the cleartext password, and the SQL name of the user it is for. algorithm specifies the encryption algorithm to use to encrypt the password. Currently supported algorithms are md5 and scram-sha-256 (on and off are also accepted as aliases for md5, for compatibility with older server versions). Note that support for scram-sha-256 was introduced in PostgreSQL version 10, and will not work correctly with older server versions. If algorithm is omitted or nil, this function will query the server for the current value of the password_encryption setting. That can block, and will fail if the current transaction is aborted, or if the connection is busy executing another query. If you wish to use the default algorithm for the server but want to avoid blocking, query password_encryption yourself before calling encrypt_password, and pass that value as the algorithm.
Return value is the encrypted password. The caller can assume the string doesn’t contain any special characters that would require escaping.
Available since PostgreSQL-10. See also corresponding libpq function.
Causes a connection to enter pipeline mode if it is currently idle or already in pipeline mode.
Raises PG::Error and has no effect if the connection is not currently idle, i.e., it has a result ready, or it is waiting for more input from the server, etc. This function does not actually send anything to the server, it just changes the libpq connection state.
See the PostgreSQL documentation.
Available since PostgreSQL-14
Returns the error message most recently generated by an operation on the connection.
Nearly all libpq functions will set a message for conn.error_message if they fail. Note that by libpq convention, a nonempty error_message result can consist of multiple lines, and will include a trailing newline.
Returns a SQL-safe version of the String str. This is the preferred way to make strings safe for inclusion in SQL queries.
Consider using exec_params, which avoids the need for passing values inside of SQL commands.
Character encoding of escaped string will be equal to client encoding of connection.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
See also convenience functions escape_literal and escape_identifier which also add proper quotes around the string.
Escapes binary data for use within an SQL command with the type bytea.
Certain byte values must be escaped (but all byte values may be escaped) when used as part of a bytea literal in an SQL statement. In general, to escape a byte, it is converted into the three digit octal number equal to the octet value, and preceded by two backslashes. The single quote (‘) and backslash () characters have special alternative escape sequences. escape_bytea performs this operation, escaping only the minimally required bytes.
Consider using exec_params, which avoids the need for passing values inside of SQL commands.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
Escape an arbitrary String str as an identifier.
This method does the same as quote_ident with a String argument, but it doesn’t support an Array argument and it makes use of libpq to process the string.
Escape an arbitrary String str as a literal.
See also PG::TextEncoder::QuotedLiteral for a type cast integrated version of this 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.
Character encoding of escaped string will be equal to client encoding of connection.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
See also convenience functions escape_literal and escape_identifier which also add proper quotes around the string.
exec(sql) {|pg_result| block }
Sends SQL query request specified by sql to PostgreSQL. On success, it returns a PG::Result instance with all result rows and columns. On failure, it raises a PG::Error.
For backward compatibility, if you pass more than one parameter to this method, it will call exec_params for you. New code should explicitly use exec_params if argument placeholders are used.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
exec is an alias for async_exec which is almost identical to sync_exec . sync_exec is implemented on the simpler synchronous command processing API of libpq, whereas async_exec is implemented on the asynchronous API and on ruby’s IO mechanisms. Only async_exec is compatible to Fiber.scheduler based asynchronous IO processing introduced in ruby-3.0. Both methods ensure that other threads can process while waiting for the server to complete the request, but sync_exec blocks all signals to be processed until the query is finished. This is most notably visible by a delayed reaction to Control+C. It’s not recommended to use explicit sync or async variants but exec instead, unless you have a good reason to do so.
See also corresponding libpq function.
exec_params(sql, params [, result_format [, type_map ]] ) {|pg_result| block }
Sends SQL query request specified by sql to PostgreSQL using placeholders for parameters.
Returns a PG::Result instance on success. On failure, it raises a PG::Error.
params is an array of the bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form:
{:value => String (value of bind parameter)
:type => Integer (oid of type of bind parameter)
:format => Integer (0 for text, 1 for binary)
}
or, it may be a String. If it is a string, that is equivalent to the hash:
{ :value => <string value>, :type => 0, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
The optional result_format should be 0 for text results, 1 for binary.
type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
The primary advantage of exec_params over exec is that parameter values can be separated from the command string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike exec, exec_params allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) This is a limitation of the underlying protocol, but has some usefulness as an extra defense against SQL-injection attacks.
See also corresponding libpq function.
exec_prepared(statement_name [, params, result_format[, type_map]] ) {|pg_result| block }
Execute prepared named statement specified by statement_name. Returns a PG::Result instance on success. On failure, it raises a PG::Error.
params is an array of the optional bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form:
{:value => String (value of bind parameter)
:format => Integer (0 for text, 1 for binary)
}
or, it may be a String. If it is a string, that is equivalent to the hash:
{ :value => <string value>, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
The optional result_format should be 0 for text results, 1 for binary.
type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec_prepared returns the value of the block.
See also corresponding libpq function.
Causes a connection to exit pipeline mode if it is currently in pipeline mode with an empty queue and no pending results.
Takes no action if not in pipeline mode. Raises PG::Error if the current statement isn’t finished processing, or PQgetResult has not been called to collect results from all previously sent query.
Available since PostgreSQL-14
Return the server_encoding of the connected database as a Ruby Encoding object. The SQL_ASCII encoding is mapped to to ASCII_8BIT.
Get type of field names.
See description at field_name_type=
Set default type of field names of results retrieved by this connection. It can be set to one of:
-
:stringto use String based field names -
:symbolto use Symbol based field names
The default is :string .
Settings the type of field names affects only future results.
See further description at PG::Result#field_name_type=
Returns true if the backend connection has been closed.
Attempts to flush any queued output data to the server. Returns true if data is successfully flushed, false if not. It can only return false if connection is in nonblocking mode. Raises PG::Error if some other failure occurred.
Returns the client encoding as a String.
Return one row of data, nil if the copy is done, or false if the call would block (only possible if nonblock is true).
If decoder is not set or nil, data is returned as binary string.
If decoder is set to a PG::Coder derivation, the return type depends on this decoder. PG::TextDecoder::CopyRow decodes the received data fields from one row of PostgreSQL’s COPY text format to an Array of Strings. Optionally the decoder can type cast the single fields to various Ruby types in one step, if PG::TextDecoder::CopyRow#type_map is set accordingly.
See also copy_data.
This function retrieves all available results on the current connection (from previously issued asynchronous commands like +send_query()+) and returns the last non-NULL result, or nil if no results are available.
If the last result contains a bad result_status, an appropriate exception is raised.
This function is similar to get_result except that it is designed to get one and only one result and that it checks the result state.
get_result() {|pg_result| block }
Blocks waiting for the next result from a call to send_query (or another asynchronous command), and returns it. Returns nil if no more results are available.
Note: call this function repeatedly until it returns nil, or else you will not be able to issue further commands.
If the optional code block is given, it will be passed result as an argument, and the PG::Result object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
Returns the server host name of the active connection. This can be a host name, an IP address, or a directory path if the connection is via Unix socket. (The path case can be distinguished because it will always be an absolute path, beginning with / .)
If the connection parameters specified both host and hostaddr, then host will return the host information. If only hostaddr was specified, then that is returned. If multiple hosts were specified in the connection parameters, host returns the host actually connected to.
If there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.
If multiple hosts were specified in the connection parameters, it is not possible to rely on the result of host until the connection is established. The status of the connection can be checked using the function Connection#status .
Returns the server IP address of the active connection. This can be the address that a host name resolved to, or an IP address provided through the hostaddr parameter. If there is an error producing the host information (perhaps if the connection has not been fully established or there was an error), it returns an empty string.
Return a String representation of the object suitable for debugging.
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’
A wrapper of set_client_encoding. defined in Ruby 1.9 or later.
value can be one of:
-
an Encoding
-
a String - a name of Encoding
-
nil- sets the client_encoding to SQL_ASCII.
Returns true if a command is busy, that is, if get_result would block. Otherwise returns false.
Returns the blocking status of the database connection. Returns true if the connection is set to nonblocking mode and false if blocking.
Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PG::Error.
Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PG::Error.
Import a file to a large object. Returns a large object Oid.
On failure, it raises a PG::Error.
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET, SEEK_CUR, and SEEK_END. (Or 0, 1, or 2.)
Open a large object of oid. Returns a large object descriptor instance on success. The mode argument specifies the mode for the opened large object,which is either INV_READ, or INV_WRITE.
If mode is omitted, the default is INV_READ.
Attempts to read len bytes from large object lo_desc, returns resulting data.
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET, SEEK_CUR, and SEEK_END. (Or 0, 1, or 2.)
Returns the current position of the large object lo_desc.
Truncates the large object lo_desc to size len.
Unlinks (deletes) the postgres large object of oid.
Writes the string buffer to the large object lo_desc. Returns the number of bytes written.
Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PG::Error.
Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PG::Error.
Import a file to a large object. Returns a large object Oid.
On failure, it raises a PG::Error.
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET, SEEK_CUR, and SEEK_END. (Or 0, 1, or 2.)
Open a large object of oid. Returns a large object descriptor instance on success. The mode argument specifies the mode for the opened large object,which is either INV_READ, or INV_WRITE.
If mode is omitted, the default is INV_READ.
Attempts to read len bytes from large object lo_desc, returns resulting data.
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET, SEEK_CUR, and SEEK_END. (Or 0, 1, or 2.)
Writes the string buffer to the large object lo_desc. Returns the number of bytes written.
Constructs and empty PG::Result with status status. status may be one of:
-
PGRES_EMPTY_QUERY -
PGRES_COMMAND_OK -
PGRES_TUPLES_OK -
PGRES_COPY_OUT -
PGRES_COPY_IN -
PGRES_BAD_RESPONSE -
PGRES_NONFATAL_ERROR -
PGRES_FATAL_ERROR -
PGRES_COPY_BOTH -
PGRES_SINGLE_TUPLE -
PGRES_TUPLES_CHUNK -
PGRES_PIPELINE_SYNC -
PGRES_PIPELINE_ABORTED
Returns a hash of the unprocessed notifications. If there is no unprocessed notifier, it returns nil.
Blocks while waiting for notification(s), or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns nil if timeout is reached, the name of the NOTIFY event otherwise. If used in block form, passes the name of the NOTIFY event, the generating pid and the optional payload string into the block.
Returns backend option string.
Returns the setting of parameter param_name, where param_name is one of
-
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 the authenticated password.
Returns the current pipeline mode status of the libpq connection.
PQpipelineStatus can return one of the following values:
-
PQ_PIPELINE_ON - The libpq connection is in pipeline mode.
-
PQ_PIPELINE_OFF - The libpq connection is not in pipeline mode.
-
PQ_PIPELINE_ABORTED - The libpq connection is in pipeline mode and an error occurred while processing the current pipeline. The aborted flag is cleared when PQgetResult returns a result of type PGRES_PIPELINE_SYNC.
Available since PostgreSQL-14
Marks a synchronization point in a pipeline by sending a sync message and flushing the send buffer. This serves as the delimiter of an implicit transaction and an error recovery point.
Raises PG::Error if the connection is not in pipeline mode or sending a sync message failed.
Available since PostgreSQL-14
Returns the connected server port number.
Prepares statement sql with name name to be executed later. Returns a PG::Result instance on success. On failure, it raises a PG::Error.
param_types is an optional parameter to specify the Oids of the types of the parameters.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query.
See also corresponding libpq function.
Interrogates the frontend/backend protocol being used.
Applications might wish to use this function to determine whether certain features are supported. Currently, the only value is 3 (3.0 protocol). The protocol version will not change after connection startup is complete, but it could theoretically change during a connection reset. The 3.0 protocol is supported by PostgreSQL server versions 7.4 and above.
PG::ConnectionBad is raised if the connection is bad.
Transmits buffer as copy data to the server. Returns true if the data was sent, false if it was not sent (false is only possible if the connection is in nonblocking mode, and this command would block).
encoder can be a PG::Coder derivation (typically PG::TextEncoder::CopyRow). This encodes the data fields given as buffer from an Array of Strings to PostgreSQL’s COPY text format inclusive proper escaping. Optionally the encoder can type cast the fields from various Ruby types in one step, if PG::TextEncoder::CopyRow#type_map is set accordingly.
Raises an exception if an error occurs.
See also copy_data.
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).
quote_ident( array ) → String
PG::Connection.quote_ident( str ) → String
PG::Connection.quote_ident( array ) → String
Returns a string that is safe for inclusion in a SQL query as an identifier. Note: this is not a quote function for values, but for identifiers.
For example, in a typical SQL query: SELECT FOO FROM MYTABLE The identifier FOO is folded to lower case, so it actually means foo. If you really want to access the case-sensitive field name FOO, use this function like conn.quote_ident('FOO'), which will return "FOO" (with double-quotes). PostgreSQL will see the double-quotes, and it will not fold to lower case.
Similarly, this function also protects against special characters, and other things that might allow SQL injection if the identifier comes from an untrusted source.
If the parameter is an Array, then all it’s values are separately quoted and then joined by a “.” character. This can be used for identifiers in the form “schema”.“table”.“column” .
This method is functional identical to the encoder PG::TextEncoder::Identifier .
If the instance method form is used and the input string character encoding is different to the connection encoding, then the string is converted to this encoding, so that the returned string is always encoded as PG::Connection#internal_encoding .
In the singleton form (PG::Connection.quote_ident) the character encoding of the result string is set to the character encoding of the input string.
Resets the backend connection. This method closes the backend connection and tries to re-connect.
Checks the status of a connection reset operation. See Connection.connect_start and connect_poll for usage information and return values.
Initiate a connection reset in a nonblocking manner. This will close the current connection and attempt to reconnect using the same connection parameters. Use reset_poll to check the status of the connection reset.
Asynchronously send command to the server. Does not block. Use in combination with conn.get_result.
Asynchronously send command to the server. Does not block. Use in combination with conn.get_result.
Sends a request for the server to flush its output buffer.
The server flushes its output buffer automatically as a result of Connection#pipeline_sync being called, or on any request when not in pipeline mode. This function is useful to cause the server to flush its output buffer in pipeline mode without establishing a synchronization point. Note that the request is not itself flushed to the server automatically; use Connection#flush if necessary.
Available since PostgreSQL-14
Marks a synchronization point in a pipeline by sending a sync message without flushing the send buffer.
This serves as the delimiter of an implicit transaction and an error recovery point. Raises PG::Error if the connection is not in pipeline mode or sending a sync message failed. Note that the message is not itself flushed to the server automatically; use flush if necessary.
Available since PostgreSQL-17
Prepares statement sql with name name to be executed later. Sends prepare command asynchronously, and returns immediately. On failure, it raises a PG::Error.
param_types is an optional parameter to specify the Oids of the types of the parameters.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query.
Sends SQL query request specified by sql to PostgreSQL for asynchronous processing, and immediately returns. On failure, it raises a PG::Error.
For backward compatibility, if you pass more than one parameter to this method, it will call send_query_params for you. New code should explicitly use send_query_params if argument placeholders are used.
Sends SQL query request specified by sql to PostgreSQL for asynchronous processing, and immediately returns. On failure, it raises a PG::Error.
params is an array of the bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form:
{:value => String (value of bind parameter)
:type => Integer (oid of type of bind parameter)
:format => Integer (0 for text, 1 for binary)
}
or, it may be a String. If it is a string, that is equivalent to the hash:
{ :value => <string value>, :type => 0, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it’s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: “SELECT $1::int”
The optional result_format should be 0 for text results, 1 for binary.
type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
→ nil
Execute prepared named statement specified by statement_name asynchronously, and returns immediately. On failure, it raises a PG::Error.
params is an array of the optional bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form:
{:value => String (value of bind parameter)
:format => Integer (0 for text, 1 for binary)
}
or, it may be a String. If it is a string, that is equivalent to the hash:
{ :value => <string value>, :format => 0 }
PostgreSQL bind parameters are represented as $1, $2, $3, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
The optional result_format should be 0 for text results, 1 for binary.
type_map can be a PG::TypeMap derivation (such as PG::BasicTypeMapForQueries). This will type cast the params from various Ruby types before transmission based on the encoders defined by the type map. When a type encoder is used the format and oid of a given bind parameter are retrieved from the encoder instead out of the hash form described above.
Returns an integer representing the server version.
Applications might use this function to determine the version of the database server they are connected to. The result is formed by multiplying the server’s major version number by 10000 and adding the minor version number. For example, version 10.1 will be returned as 100001, and version 11.0 will be returned as 110000.
PG::ConnectionBad is raised if the connection is bad.
Prior to major version 10, PostgreSQL used three-part version numbers in which the first two parts together represented the major version. For those versions, PQserverVersion uses two digits for each part; for example version 9.1.5 will be returned as 90105, and version 9.2.0 will be returned as 90200.
Therefore, for purposes of determining feature compatibility, applications should divide the result of PQserverVersion by 100 not 10000 to determine a logical major version number. In all release series, only the last two digits differ between minor releases (bug-fix releases).
Select chunked mode for the currently-executing query.
This function is similar to set_single_row_mode, except that it specifies retrieval of up to chunk_size rows per PGresult, not necessarily just one row. This function can only be called immediately after send_query or one of its sibling functions, before any other operation on the connection such as consume_input or get_result. If called at the correct time, the function activates chunked mode for the current query. Otherwise the mode stays unchanged and the function raises an error. In any case, the mode reverts to normal after completion of the current query.
Example:
conn.send_query( "your SQL command" ) conn.set_chunked_rows_mode(10) loop do res = conn.get_result or break res.check res.each do |row| # do something with the received max. 10 rows end end
Available since PostgreSQL-17
Sets the client encoding to the encoding String.
If Ruby has its Encoding.default_internal set, set PostgreSQL’s client_encoding to match. Returns the new Encoding, or nil if the default internal encoding wasn’t set.
Sets connection’s context display mode to context_visibility and returns the previous setting. Available settings are:
-
PQSHOW_CONTEXT_NEVER
-
PQSHOW_CONTEXT_ERRORS
-
PQSHOW_CONTEXT_ALWAYS
This mode controls whether the CONTEXT field is included in messages (unless the verbosity setting is TERSE, in which case CONTEXT is never shown). The NEVER mode never includes CONTEXT, while ALWAYS always includes it if available. In ERRORS mode (the default), CONTEXT fields are included only for error messages, not for notices and warnings.
Changing this mode does not affect the messages available from already-existing PG::Result objects, only subsequently-created ones. (But see PG::Result#verbose_error_message if you want to print a previous error with a different display mode.)
See also corresponding libpq function.
Sets connection’s verbosity to verbosity and returns the previous setting. Available settings are:
-
PQERRORS_TERSE
-
PQERRORS_DEFAULT
-
PQERRORS_VERBOSE
-
PQERRORS_SQLSTATE
Changing the verbosity does not affect the messages available from already-existing PG::Result objects, only subsequently-created ones. (But see PG::Result#verbose_error_message if you want to print a previous error with a different verbosity.)
See also corresponding libpq function.
See set_notice_receiver for the description of what this and the notice_processor methods do.
This function takes a new block to act as the notice processor and returns the Proc object previously set, or nil if it was previously the default. The block should accept a single String object.
If you pass no arguments, it will reset the handler to the default.
Notice and warning messages generated by the server are not returned by the query execution functions, since they do not imply failure of the query. Instead they are passed to a notice handling function, and execution continues normally after the handler returns. The default notice handling function prints the message on stderr, but the application can override this behavior by supplying its own handling function.
For historical reasons, there are two levels of notice handling, called the notice receiver and notice processor. The default behavior is for the notice receiver to format the notice and pass a string to the notice processor for printing. However, an application that chooses to provide its own notice receiver will typically ignore the notice processor layer and just do all the work in the notice receiver.
This function takes a new block to act as the handler, which should accept a single parameter that will be a PG::Result object, and returns the Proc object previously set, or nil if it was previously the default.
If you pass no arguments, it will reset the handler to the default.
Note: The result passed to the block should not be used outside of the block, since the corresponding C object could be freed after the block finishes.
To enter single-row mode, call this method immediately after a successful call of send_query (or a sibling function). This mode selection is effective only for the currently executing query. Then call Connection#get_result repeatedly, until it returns nil.
Each (but the last) received Result has exactly one row and a Result#result_status of PGRES_SINGLE_TUPLE. The last Result has zero rows and is used to indicate a successful execution of the query. All of these Result objects will contain the same row description data (column names, types, etc) that an ordinary Result object for the query would have.
Caution: While processing a query, the server may return some rows and then encounter an error, causing the query to be aborted. Ordinarily, pg discards any such rows and reports only the error. But in single-row or chunked mode, some rows may have already been returned to the application. Hence, the application will see some PGRES_SINGLE_TUPLE or PGRES_TUPLES_CHUNK PG::Result objects followed by a PG::Error raised in get_result. For proper transactional behavior, the application must be designed to discard or undo whatever has been done with the previously-processed rows, if the query ultimately fails.
Example:
conn.send_query( "your SQL command" ) conn.set_single_row_mode loop do res = conn.get_result or break res.check res.each do |row| # do something with the received row end end
Sets the nonblocking status of the connection. In the blocking state, calls to send_query will block until the message is sent to the server, but will not wait for the query results. In the nonblocking state, calls to send_query will return an error if the socket is not ready for writing. Note: This function does not affect exec, because that function doesn’t return until the server has processed the query and returned the results.
Returns nil.
This method is deprecated. Please use the more portable method socket_io .
Returns the socket’s file descriptor for this connection. IO.for_fd() can be used to build a proper IO object to the socket. If you do so, you will likely also want to set autoclose=false on it to prevent Ruby from closing the socket to PostgreSQL if it goes out of scope. Alternatively, you can use socket_io, which creates an IO that’s associated with the connection object itself, and so won’t go out of scope until the connection does.
Note: On Windows the file descriptor is not usable, since it can not be used to build a Ruby IO object.
Fetch an IO object created from the Connection’s underlying socket. This object can be used per socket_io.wait_readable, socket_io.wait_writable or for IO.select to wait for events while running asynchronous API calls. IO#wait_*able is Fiber.scheduler compatible in contrast to IO.select.
The IO object can change while the connection is established, but is memorized afterwards. So be sure not to cache the IO object, but repeat calling conn.socket_io instead.
Using this method also works on Windows in contrast to using socket . It also avoids the problem of the underlying connection being closed by Ruby when an IO created using IO.for_fd(conn.socket) goes out of scope.
Returns SSL-related information about the connection.
The list of available attributes varies depending on the SSL library being used, and the type of connection. If an attribute is not available, returns nil.
The following attributes are commonly available:
library
Name of the SSL implementation in use. (Currently, only “OpenSSL” is implemented)
protocol
SSL/TLS version in use. Common values are “SSLv2”, “SSLv3”, “TLSv1”, “TLSv1.1” and “TLSv1.2”, but an implementation may return other strings if some other protocol is used.
key_bits
Number of key bits used by the encryption algorithm.
cipher
A short name of the ciphersuite used, e.g. “DHE-RSA-DES-CBC3-SHA”. The names are specific to each SSL implementation.
compression
If SSL compression is in use, returns the name of the compression algorithm, or “on” if compression is used but the algorithm is not known. If compression is not in use, returns “off”.
See also ssl_attribute_names and the corresponding libpq function.
Return an array of SSL attribute names available.
See also ssl_attribute
Returns SSL-related information about the connection as key/value pairs
The available attributes varies depending on the SSL library being used, and the type of connection.
See also ssl_attribute
Returns true if the connection uses SSL/TLS, false if not.
Returns the status of the connection, which is one:
PG::Constants::CONNECTION_OK PG::Constants::CONNECTION_BAD
… and other constants of kind PG::Constants::CONNECTION_*
This method returns the status of the last command from memory. It doesn’t do any socket access hence is not suitable to test the connectivity. See check_socket for a way to verify the socket state.
Example:
PG.constants.grep(/CONNECTION_/).find{|c| PG.const_get(c) == conn.status} # => :CONNECTION_OK
This function has the same behavior as async_close_portal, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but close_portal instead, unless you have a good reason to do so.
Available since PostgreSQL-17.
This function has the same behavior as async_close_prepared, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but close_prepared instead, unless you have a good reason to do so.
Available since PostgreSQL-17.
This function has the same behavior as async_describe_portal, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but describe_portal instead, unless you have a good reason to do so.
This function has the same behavior as async_describe_prepared, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but describe_prepared instead, unless you have a good reason to do so.
sync_exec(sql) {|pg_result| block }
This function has the same behavior as async_exec, but is implemented using the synchronous command processing API of libpq. It’s not recommended to use explicit sync or async variants but exec instead, unless you have a good reason to do so.
Both sync_exec and async_exec release the GVL while waiting for server response, so that concurrent threads will get executed. However async_exec has two advantages:
-
async_execcan be aborted by signals (like Ctrl-C), whileexecblocks signal processing until the query is answered. -
Ruby VM gets notified about IO blocked operations and can pass them through
Fiber.scheduler. So onlyasync_*methods are compatible to event based schedulers like the async gem.
sync_exec_params(sql, params[, result_format[, type_map]] ) {|pg_result| block }
This function has the same behavior as async_exec_params, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but exec_params instead, unless you have a good reason to do so.
sync_exec_prepared(statement_name [, params, result_format[, type_map]] ) {|pg_result| block }
This function has the same behavior as async_exec_prepared, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but exec_prepared instead, unless you have a good reason to do so.
This function has the same behavior as async_get_last_result, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but get_last_result instead, unless you have a good reason to do so.
This function has the same behavior as async_pipeline_sync, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but pipeline_sync instead, unless you have a good reason to do so.
Available since PostgreSQL-14
This function has the same behavior as async_prepare, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but prepare instead, unless you have a good reason to do so.
This function has the same behavior as async_set_client_encoding, but is implemented using the synchronous command processing API of libpq. See async_exec for the differences between the two API variants. It’s not recommended to use explicit sync or async variants but set_client_encoding instead, unless you have a good reason to do so.
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.
Executes a BEGIN at the start of the block, and a COMMIT at the end of the block, or ROLLBACK if any exception occurs.
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)
Obsolete function.
Returns the default TypeMap that is currently set for type casts of query bind parameters.
Set the default TypeMap that is used for type casts of query bind parameters.
typemap must be a kind of PG::TypeMap .
Returns the default TypeMap that is currently set for type casts of result values.
Set the default TypeMap that is used for type casts of result values.
typemap must be a kind of PG::TypeMap .
Converts an escaped string representation of binary data into binary data — the reverse of escape_bytea. This is needed when retrieving bytea data in text format, but not when retrieving it in binary format.
Disables the message tracing.
Returns the authenticated user name.
Blocks while waiting for notification(s), or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns nil if timeout is reached, the name of the NOTIFY event otherwise. If used in block form, passes the name of the NOTIFY event, the generating pid and the optional payload string into the block.