Class | PGconn |
In: |
ext/pg.c
|
Parent: | Object |
The class to access PostgreSQL RDBMS, based on the libpq interface, provides convenient OO methods to interact with PostgreSQL.
For example, to send query to the database on the localhost:
require 'pg' conn = PGconn.open(:dbname => 'test') res = conn.exec('SELECT $1 AS a, $2 AS b, $3 AS c',[1, 2, nil]) # Equivalent to: # res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
See the PGresult class for information on working with the results of a query.
CONNECTION_OK | = | PGconn CLASS CONSTANTS | Connection Status | |
CONNECTION_BAD | = | INT2FIX(CONNECTION_BAD) | ||
CONNECTION_STARTED | = | PGconn CLASS CONSTANTS | Nonblocking connection status | |
CONNECTION_MADE | = | INT2FIX(CONNECTION_MADE) | ||
CONNECTION_AWAITING_RESPONSE | = | INT2FIX(CONNECTION_AWAITING_RESPONSE) | ||
CONNECTION_AUTH_OK | = | INT2FIX(CONNECTION_AUTH_OK) | ||
CONNECTION_SSL_STARTUP | = | INT2FIX(CONNECTION_SSL_STARTUP) | ||
CONNECTION_SETENV | = | INT2FIX(CONNECTION_SETENV) | ||
PGRES_POLLING_READING | = | PGconn CLASS CONSTANTS | Nonblocking connection polling status | |
PGRES_POLLING_WRITING | = | INT2FIX(PGRES_POLLING_WRITING) | ||
PGRES_POLLING_FAILED | = | INT2FIX(PGRES_POLLING_FAILED) | ||
PGRES_POLLING_OK | = | INT2FIX(PGRES_POLLING_OK) | ||
PQTRANS_IDLE | = | PGconn CLASS CONSTANTS | Transaction Status | |
PQTRANS_ACTIVE | = | INT2FIX(PQTRANS_ACTIVE) | ||
PQTRANS_INTRANS | = | INT2FIX(PQTRANS_INTRANS) | ||
PQTRANS_INERROR | = | INT2FIX(PQTRANS_INERROR) | ||
PQTRANS_UNKNOWN | = | INT2FIX(PQTRANS_UNKNOWN) | ||
PQERRORS_TERSE | = | PGconn CLASS CONSTANTS | Error Verbosity | |
PQERRORS_DEFAULT | = | INT2FIX(PQERRORS_DEFAULT) | ||
PQERRORS_VERBOSE | = | INT2FIX(PQERRORS_VERBOSE) | ||
INV_WRITE | = | PGconn CLASS CONSTANTS | Large Objects | |
INV_READ | = | INT2FIX(INV_READ) | ||
SEEK_SET | = | INT2FIX(SEEK_SET) | ||
SEEK_CUR | = | INT2FIX(SEEK_CUR) | ||
SEEK_END | = | INT2FIX(SEEK_END) |
Returns an array of hashes. Each hash has the keys:
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.
connection_hash example: +PGconn.connect(:dbname=>’test’, :port=>5432) connection_string example: +PGconn.connect("dbname=test port=5432") connection_hash example: +PGconn.connect(nil,5432,nil,nil,’test’,nil,nil)
On failure, it raises a PGError exception.
connection_hash example: +PGconn.connect(:dbname=>’test’, :port=>5432) connection_string example: +PGconn.connect("dbname=test port=5432") connection_hash example: +PGconn.connect(nil,5432,nil,nil,’test’,nil,nil)
On failure, it raises a PGError exception.
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.
Returns an array of hashes. Each hash has the keys:
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.
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.
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.
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.
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.
call-seq
conn.lo_lseek( lo_desc, offset, whence ) -> Fixnum
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET, SEEK_CUR, and SEEK_END. (Or 0, 1, or 2.)
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 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.
Returns true if a command is busy, that is, if PQgetResult would block. Otherwise returns false.
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.