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.
CONNECT_ARGUMENT_ORDER | = | %w[host port options tty dbname user password] | The order the options are passed to the ::connect method. | |
VERSION | = | rb_str_new2(VERSION) | Library version | |
CONNECTION_OK | = | INT2FIX(CONNECTION_OK) | Connection succeeded | |
CONNECTION_BAD | = | INT2FIX(CONNECTION_BAD) | Connection failed | |
CONNECTION_STARTED | = | INT2FIX(CONNECTION_STARTED) | Waiting for connection to be made. | |
CONNECTION_MADE | = | INT2FIX(CONNECTION_MADE) | Connection OK; waiting to send. | |
CONNECTION_AWAITING_RESPONSE | = | INT2FIX(CONNECTION_AWAITING_RESPONSE) | Waiting for a response from the server. | |
CONNECTION_AUTH_OK | = | INT2FIX(CONNECTION_AUTH_OK) | Received authentication; waiting for backend start-up to finish. | |
CONNECTION_SSL_STARTUP | = | INT2FIX(CONNECTION_SSL_STARTUP) | Negotiating SSL encryption. | |
CONNECTION_SETENV | = | INT2FIX(CONNECTION_SETENV) | Negotiating environment-driven parameter settings. | |
PGRES_POLLING_READING | = | INT2FIX(PGRES_POLLING_READING) | Async connection is waiting to read | |
PGRES_POLLING_WRITING | = | INT2FIX(PGRES_POLLING_WRITING) | Async connection is waiting to write | |
PGRES_POLLING_FAILED | = | INT2FIX(PGRES_POLLING_FAILED) | Async connection failed or was reset | |
PGRES_POLLING_OK | = | INT2FIX(PGRES_POLLING_OK) | Async connection succeeded | |
PQTRANS_IDLE | = | INT2FIX(PQTRANS_IDLE) | Transaction is currently idle (transaction_status) | |
PQTRANS_ACTIVE | = | INT2FIX(PQTRANS_ACTIVE) | Transaction is currently active; query has been sent to the server, but not yet completed. (transaction_status) | |
PQTRANS_INTRANS | = | INT2FIX(PQTRANS_INTRANS) | Transaction is currently idle, in a valid transaction block (transaction_status) | |
PQTRANS_INERROR | = | INT2FIX(PQTRANS_INERROR) | Transaction is currently idle, in a failed transaction block (transaction_status) | |
PQTRANS_UNKNOWN | = | INT2FIX(PQTRANS_UNKNOWN) | Transaction‘s connection is bad (transaction_status) | |
PQERRORS_TERSE | = | INT2FIX(PQERRORS_TERSE) | Terse error verbosity level (set_error_verbosity) | |
PQERRORS_DEFAULT | = | INT2FIX(PQERRORS_DEFAULT) | Default error verbosity level (set_error_verbosity) | |
PQERRORS_VERBOSE | = | INT2FIX(PQERRORS_VERBOSE) | Verbose error verbosity level (set_error_verbosity) | |
INV_WRITE | = | INT2FIX(INV_WRITE) | Flag for lo_creat, lo_open — open for writing | |
INV_READ | = | INT2FIX(INV_READ) | Flag for lo_creat, lo_open — open for reading | |
SEEK_SET | = | INT2FIX(SEEK_SET) | Flag for lo_lseek — seek from object start | |
SEEK_CUR | = | INT2FIX(SEEK_CUR) | Flag for lo_lseek — seek from current position | |
SEEK_END | = | INT2FIX(SEEK_END) | Flag for lo_lseek — seek from object end |
Returns an array of hashes. Each hash has the keys:
This is an asynchronous version of PGconn.connect().
Use PGconn#connect_poll to poll the status of the connection.
NOTE: this does not set the connection‘s client_encoding for you if Encoding.default_internal is set. To set it after the connection is established, call PGconn#internal_encoding=. You can also set it automatically by setting ENV[‘PGCLIENTENCODING’], or include the ‘options’ connection parameter.
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.
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.
Connection instance method for versions of 8.1 and higher of libpq uses PQescapeStringConn, which is safer. Avoid calling as a class method, the class method uses the deprecated PQescapeString() API function.
Returns a SQL-safe version of the String str. This is the preferred way to make strings safe for inclusion in SQL queries.
Consider using exec_params, which avoids the need for passing values inside of SQL commands.
Encoding of escaped string will be equal to client encoding of connection.
Create a connection to the specified server.
Examples:
# Connect using all defaults PGconn.connect # As a Hash PGconn.connect( :dbname => 'test', :port => 5432 ) # As a String PGconn.connect( "dbname=test port=5432" ) # As an Array PGconn.connect( nil, 5432, nil, nil, 'test', nil, nil )
If the Ruby default internal encoding is set (i.e., Encoding.default_internal != nil), the connection will have its client_encoding set accordingly.
Raises a PGError if the connection fails.
Parse the connection args into a connection-parameter string. See PGconn.new for valid arguments.
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.
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.
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.
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. (Only implemented in PostgreSQL >= 8.0)
Returns nil on success, or a string containing the error message if a failure occurs.
Returns an array of hashes. Each hash has the keys:
Returns one of:
Example:
conn = PGconn.connect_start("dbname=mydatabase") socket = IO.for_fd(conn.socket) status = conn.connect_poll while(status != PGconn::PGRES_POLLING_OK) do # do some work while waiting for the connection to complete if(status == PGconn::PGRES_POLLING_READING) if(not select([socket], [], [], 10.0)) raise "Asynchronous connection timed out!" end elsif(status == PGconn::PGRES_POLLING_WRITING) if(not select([], [socket], [], 10.0)) raise "Asynchronous connection timed out!" end end status = conn.connect_poll end # now conn.status == CONNECTION_OK, and connection # is ready.
Returns true if the authentication method required a password, but none was available. false otherwise.
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.
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.
Connection instance method for versions of 8.1 and higher of libpq uses PQescapeStringConn, which is safer. Avoid calling as a class method, the class method uses the deprecated PQescapeString() API function.
Returns a SQL-safe version of the String str. This is the preferred way to make strings safe for inclusion in SQL queries.
Consider using exec_params, which avoids the need for passing values inside of SQL commands.
Encoding of escaped string will be equal to client encoding of connection.
Sends SQL query request specified by sql to PostgreSQL. Returns a PGresult instance on success. On failure, it raises a PGError exception.
params is an optional array of the bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form: {:value => String (value of bind parameter) :type => Fixnum (oid of type of bind parameter) :format => Fixnum (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :type => 0, :format => 0 }
PostgreSQL bind parameters are represented as $1, $1, $2, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
If the types are not specified, they will be inferred by PostgreSQL. Instead of specifying type oids, it‘s recommended to simply add explicit casts in the query to ensure that the right type is used.
For example: "SELECT $1::int"
The optional result_format should be 0 for text results, 1 for binary.
If the optional code block is given, it will be passed result as an argument, and the PGresult object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
Execute prepared named statement specified by statement_name. Returns a PGresult instance on success. On failure, it raises a PGError exception.
params is an array of the optional bind parameters for the SQL query. Each element of the params array may be either:
a hash of the form: {:value => String (value of bind parameter) :format => Fixnum (0 for text, 1 for binary) } or, it may be a String. If it is a string, that is equivalent to the hash: { :value => <string value>, :format => 0 }
PostgreSQL bind parameters are represented as $1, $1, $2, etc., inside the SQL query. The 0th element of the params array is bound to $1, the 1st element is bound to $2, etc. nil is treated as NULL.
The optional result_format should be 0 for text results, 1 for binary.
If the optional code block is given, it will be passed result as an argument, and the PGresult object will automatically be cleared when the block terminates. In this instance, conn.exec_prepared returns the value of the block.
defined in Ruby 1.9 or later.
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).
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.
Blocks waiting for the next result from a call to +PGconn#send_query+ (or another asynchronous command), and returns it. Returns nil if no more results are available.
Note: call this function repeatedly until it returns nil, or else you will not be able to issue further commands.
If the optional code block is given, it will be passed result as an argument, and the PGresult object will automatically be cleared when the block terminates. In this instance, conn.exec returns the value of the block.
defined in Ruby 1.9 or later.
Returns:
A wrapper of +PGconn#set_client_encoding+. defined in Ruby 1.9 or later.
value can be one of:
Returns true if a command is busy, that is, if PQgetResult would block. Otherwise returns false.
Returns true if a command is busy, that is, if PQgetResult would block. Otherwise returns false.
Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PGError exception.
Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PGError exception.
Import a file to a large object. Returns a large object Oid.
On failure, it raises a PGError exception.
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.
Returns a hash of the unprocessed notifications. If there is no unprocessed notifier, it returns nil.
Returns the setting of parameter param_name, where param_name is one of
Returns nil if the value of the parameter is not known.
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.
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.)
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.
Sends end-of-data indication to the server.
error_message is an optional parameter, and if set, forces the COPY command to fail with the string error_message.
Returns true if the end-of-data was sent, false if it was not sent (false is only possible if the connection is in nonblocking mode, and this command would block).
Returns 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.
Checks the status of a connection reset operation. See PGconn#connect_start and PGconn#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 PGconn#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+.
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.
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.
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.
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.
Sets connection‘s verbosity to verbosity and returns the previous setting. Available settings are:
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.
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.
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.
Enables tracing message passing between backend. The trace message will be written to the stream stream, which must implement a method fileno that returns a writable file descriptor.
returns 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)
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.
Blocks while waiting for notification(s), or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns nil if timeout is reached, the name of the NOTIFY event otherwise. If used in block form, passes the name of the NOTIFY event and the generating pid into the block.
Under PostgreSQL 9.0 and later, if the notification is sent with the optional payload string, it will be given to the block as the third argument.