Class: PG::Connection
- Inherits:
-
Object
- Object
- PG::Connection
- Defined in:
- lib/pg/connection.rb,
ext/pg_connection.c
Overview
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 to #async_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.
Defined Under Namespace
Modules: Pollable
Constant Summary
Constants included from Constants
PG::Constants::CONNECTION_ALLOCATED, PG::Constants::CONNECTION_AUTH_OK, PG::Constants::CONNECTION_AWAITING_RESPONSE, PG::Constants::CONNECTION_BAD, PG::Constants::CONNECTION_CHECK_STANDBY, PG::Constants::CONNECTION_CHECK_TARGET, PG::Constants::CONNECTION_CHECK_WRITABLE, PG::Constants::CONNECTION_CONSUME, PG::Constants::CONNECTION_GSS_STARTUP, PG::Constants::CONNECTION_MADE, PG::Constants::CONNECTION_NEEDED, PG::Constants::CONNECTION_OK, PG::Constants::CONNECTION_SETENV, PG::Constants::CONNECTION_SSL_STARTUP, PG::Constants::CONNECTION_STARTED, PG::Constants::DEF_PGPORT, PG::Constants::INVALID_OID, PG::Constants::INV_READ, PG::Constants::INV_WRITE, PG::Constants::InvalidOid, PG::Constants::PGRES_BAD_RESPONSE, PG::Constants::PGRES_COMMAND_OK, PG::Constants::PGRES_COPY_BOTH, PG::Constants::PGRES_COPY_IN, PG::Constants::PGRES_COPY_OUT, PG::Constants::PGRES_EMPTY_QUERY, PG::Constants::PGRES_FATAL_ERROR, PG::Constants::PGRES_NONFATAL_ERROR, PG::Constants::PGRES_PIPELINE_ABORTED, PG::Constants::PGRES_PIPELINE_SYNC, PG::Constants::PGRES_POLLING_FAILED, PG::Constants::PGRES_POLLING_OK, PG::Constants::PGRES_POLLING_READING, PG::Constants::PGRES_POLLING_WRITING, PG::Constants::PGRES_SINGLE_TUPLE, PG::Constants::PGRES_TUPLES_CHUNK, PG::Constants::PGRES_TUPLES_OK, PG::Constants::PG_DIAG_COLUMN_NAME, PG::Constants::PG_DIAG_CONSTRAINT_NAME, PG::Constants::PG_DIAG_CONTEXT, PG::Constants::PG_DIAG_DATATYPE_NAME, PG::Constants::PG_DIAG_INTERNAL_POSITION, PG::Constants::PG_DIAG_INTERNAL_QUERY, PG::Constants::PG_DIAG_MESSAGE_DETAIL, PG::Constants::PG_DIAG_MESSAGE_HINT, PG::Constants::PG_DIAG_MESSAGE_PRIMARY, PG::Constants::PG_DIAG_SCHEMA_NAME, PG::Constants::PG_DIAG_SEVERITY, PG::Constants::PG_DIAG_SEVERITY_NONLOCALIZED, PG::Constants::PG_DIAG_SOURCE_FILE, PG::Constants::PG_DIAG_SOURCE_FUNCTION, PG::Constants::PG_DIAG_SOURCE_LINE, PG::Constants::PG_DIAG_SQLSTATE, PG::Constants::PG_DIAG_STATEMENT_POSITION, PG::Constants::PG_DIAG_TABLE_NAME, PG::Constants::PQERRORS_DEFAULT, PG::Constants::PQERRORS_SQLSTATE, PG::Constants::PQERRORS_TERSE, PG::Constants::PQERRORS_VERBOSE, PG::Constants::PQPING_NO_ATTEMPT, PG::Constants::PQPING_NO_RESPONSE, PG::Constants::PQPING_OK, PG::Constants::PQPING_REJECT, PG::Constants::PQSHOW_CONTEXT_ALWAYS, PG::Constants::PQSHOW_CONTEXT_ERRORS, PG::Constants::PQSHOW_CONTEXT_NEVER, PG::Constants::PQTRANS_ACTIVE, PG::Constants::PQTRANS_IDLE, PG::Constants::PQTRANS_INERROR, PG::Constants::PQTRANS_INTRANS, PG::Constants::PQTRANS_UNKNOWN, PG::Constants::PQ_PIPELINE_ABORTED, PG::Constants::PQ_PIPELINE_OFF, PG::Constants::PQ_PIPELINE_ON, PG::Constants::SEEK_CUR, PG::Constants::SEEK_END, PG::Constants::SEEK_SET
Class Method Summary collapse
-
.async_api=(enable) ⇒ Object
Switch between sync and async libpq API.
- .async_send_api=(enable) ⇒ Object
-
.conndefaults ⇒ Object
call-seq: PG::Connection.conndefaults() -> Array.
-
.conndefaults_hash ⇒ Object
Return the Postgres connection defaults structure as a Hash keyed by option keyword (as a Symbol).
-
.connect_hash_to_string(hash) ⇒ Object
Convert Hash options to connection String.
-
.connect_start(*args) ⇒ Object
This is an asynchronous version of PG::Connection.new.
-
.conninfo_parse(conninfo) ⇒ Object
call-seq: PG::Connection.conninfo_parse(conninfo_string) -> Array.
-
.PG::Connection.encrypt_password(password, username) ⇒ String
This is an older, deprecated version of #encrypt_password.
-
.escape_bytea(string) ⇒ String
Escapes binary data for use within an SQL command with the type
bytea
. -
.escape_string(str) ⇒ String
Returns a SQL-safe version of the String str.
-
.new(*args) ⇒ Object
(also: async_connect, connect, open, setdb, setdblogin)
call-seq: PG::Connection.new -> conn PG::Connection.new(connection_hash) -> conn PG::Connection.new(connection_string) -> conn PG::Connection.new(host, port, options, tty, dbname, user, password) -> conn.
-
.parse_connect_args(*args) ⇒ Object
Parse the connection
args
into a connection-parameter string. -
.ping(*args) ⇒ Object
(also: async_ping)
call-seq: PG::Connection.ping(connection_hash) -> Integer PG::Connection.ping(connection_string) -> Integer PG::Connection.ping(host, port, options, tty, dbname, login, password) -> Integer.
-
.quote_connstr(value) ⇒ Object
Quote a single
value
for use in a connection-parameter string. -
.quote_ident(str_or_array) ⇒ Object
Returns a string that is safe for inclusion in a SQL query as an identifier.
- .sync_connect(*args) ⇒ Object
- .sync_ping(*args) ⇒ Object
-
.PG::Connection.unescape_bytea(string) ⇒ Object
Converts an escaped string representation of binary data into binary data — the reverse of #escape_bytea.
Instance Method Summary collapse
-
#backend_key ⇒ Integer
Returns the key of the backend server process for this connection.
-
#backend_pid ⇒ Integer
Returns the process ID of the backend server process for this connection.
-
#block([ timeout ]) ⇒ Boolean
Blocks until the server is no longer busy, or until the optional timeout is reached, whichever comes first.
-
#cancel ⇒ Object
(also: #async_cancel)
PostgreSQL < 17.
-
#check_socket ⇒ Object
Read all pending socket input to internal memory and raise an exception in case of errors.
-
#close_portal(portal_name) ⇒ PG::Result
(also: #async_close_portal)
Submits a request to close the specified portal, and waits for completion.
-
#close_prepared(statement_name) ⇒ PG::Result
(also: #async_close_prepared)
Submits a request to close the specified prepared statement, and waits for completion.
-
#conndefaults ⇒ Object
Returns an array of Hashes with connection defaults.
-
#conndefaults_hash ⇒ Object
Returns a Hash with connection defaults.
-
#connect_poll ⇒ Integer
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. -
#connection_needs_password ⇒ Boolean
Returns
true
if the authentication method required a password, but none was available. -
#connection_used_password ⇒ Boolean
Returns
true
if the authentication method used a caller-supplied password,false
otherwise. -
#conninfo ⇒ Hash
Returns the connection options used by a live connection.
-
#conninfo_hash ⇒ Object
Return the Postgres connection info structure as a Hash keyed by option keyword (as a Symbol).
-
#consume_input ⇒ Object
If input is available from the server, consume it.
-
#copy_data(sql, coder = nil) ⇒ Object
call-seq: conn.copy_data( sql [, coder] ) {|sql_result| … } -> PG::Result.
-
#db ⇒ Object
Returns the connected database name.
-
#decoder_for_get_copy_data ⇒ PG::Coder
Returns the default coder object that is currently set for type casting of received data by #get_copy_data .
-
#decoder_for_get_copy_data=(decoder) ⇒ Object
Set the default coder that is used for type casting of received data by #get_copy_data .
-
#describe_portal(portal_name) ⇒ PG::Result
(also: #async_describe_portal)
Retrieve information about the portal portal_name.
-
#describe_prepared(statement_name) ⇒ PG::Result
(also: #async_describe_prepared)
Retrieve information about the prepared statement statement_name.
-
#discard_results ⇒ Object
Silently discard any prior query result that application didn’t eat.
-
#encoder_for_put_copy_data ⇒ PG::Coder
Returns the default coder object that is currently set for type casting of parameters to #put_copy_data .
-
#encoder_for_put_copy_data=(encoder) ⇒ Object
Set the default coder that is used for type casting of parameters to #put_copy_data .
-
#encrypt_password(password, username, algorithm = nil) ⇒ Object
(also: #async_encrypt_password)
call-seq: conn.encrypt_password( password, username, algorithm=nil ) -> String.
-
#enter_pipeline_mode ⇒ nil
Causes a connection to enter pipeline mode if it is currently idle or already in pipeline mode.
-
#error_message ⇒ String
Returns the error message most recently generated by an operation on the connection.
-
#escape_bytea(string) ⇒ String
Escapes binary data for use within an SQL command with the type
bytea
. -
#escape_identifier(str) ⇒ String
Escape an arbitrary String
str
as an identifier. -
#escape_literal(str) ⇒ String
Escape an arbitrary String
str
as a literal. -
#escape_string(str) ⇒ String
(also: #escape)
Returns a SQL-safe version of the String str.
-
#exec(*args) ⇒ Object
(also: #async_exec)
Sends SQL query request specified by sql to PostgreSQL.
-
#exec_params(*args) ⇒ Object
(also: #async_exec_params)
Sends SQL query request specified by
sql
to PostgreSQL using placeholders for parameters. -
#exec_prepared(*args) ⇒ Object
(also: #async_exec_prepared)
Execute prepared named statement specified by statement_name.
-
#exit_pipeline_mode ⇒ nil
Causes a connection to exit pipeline mode if it is currently in pipeline mode with an empty queue and no pending results.
-
#external_encoding ⇒ Encoding
Return the
server_encoding
of the connected database as a Ruby Encoding object. -
#field_name_type ⇒ Symbol
Get type of field names.
-
#field_name_type=(Symbol) ⇒ Object
Set default type of field names of results retrieved by this connection.
-
#finish ⇒ Object
(also: #close)
Closes the backend connection.
-
#finished? ⇒ Boolean
Returns
true
if the backend connection has been closed. -
#flush ⇒ Boolean
(also: #async_flush)
Attempts to flush any queued output data to the server.
-
#get_client_encoding ⇒ String
Returns the client encoding as a String.
-
#get_copy_data(async = false, decoder = nil) ⇒ Object
(also: #async_get_copy_data)
call-seq: conn.get_copy_data( [ nonblock = false [, decoder = nil ]] ) -> Object.
-
#get_last_result ⇒ PG::Result
(also: #async_get_last_result)
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. -
#get_result ⇒ Object
(also: #async_get_result)
call-seq: conn.get_result() -> PG::Result conn.get_result() {|pg_result| block }.
-
#host ⇒ Object
Returns the server host name of the active connection.
-
#hostaddr ⇒ Object
Returns the server IP address of the active connection.
-
#inspect ⇒ Object
Return a String representation of the object suitable for debugging.
-
#internal_encoding ⇒ Encoding
defined in Ruby 1.9 or later.
-
#internal_encoding=(value) ⇒ Object
A wrapper of #set_client_encoding.
-
#is_busy ⇒ Boolean
Returns
true
if a command is busy, that is, if #get_result would block. -
#isnonblocking ⇒ Object
(also: #async_isnonblocking, #nonblocking?)
call-seq: conn.isnonblocking() -> Boolean.
-
#lo_close(lo_desc) ⇒ nil
(also: #loclose)
Closes the postgres large object of lo_desc.
-
#lo_creat([mode]) ⇒ Integer
(also: #locreat)
Creates a large object with mode mode.
-
#lo_create(oid) ⇒ Integer
(also: #locreate)
Creates a large object with oid oid.
-
#lo_export(oid, file) ⇒ nil
(also: #loexport)
Saves a large object of oid to a file.
-
#lo_import(file) ⇒ Integer
(also: #loimport)
Import a file to a large object.
-
#lo_lseek(lo_desc, offset, whence) ⇒ Integer
(also: #lolseek, #lo_seek, #loseek)
Move the large object pointer lo_desc to offset offset.
-
#lo_open(oid, [mode]) ⇒ Integer
(also: #loopen)
Open a large object of oid.
-
#lo_read(lo_desc, len) ⇒ String
(also: #loread)
Attempts to read len bytes from large object lo_desc, returns resulting data.
-
#lo_tell(lo_desc) ⇒ Integer
(also: #lotell)
Returns the current position of the large object lo_desc.
-
#lo_truncate(lo_desc, len) ⇒ nil
(also: #lotruncate)
Truncates the large object lo_desc to size len.
-
#lo_unlink(oid) ⇒ nil
(also: #lounlink)
Unlinks (deletes) the postgres large object of oid.
-
#lo_write(lo_desc, buffer) ⇒ Integer
(also: #lowrite)
Writes the string buffer to the large object lo_desc.
-
#make_empty_pgresult(status) ⇒ PG::Result
Constructs and empty PG::Result with status status.
-
#notifies ⇒ Object
Returns a hash of the unprocessed notifications.
-
#options ⇒ Object
Returns backend option string.
-
#parameter_status(param_name) ⇒ String
Returns the setting of parameter param_name, where param_name is one of *
server_version
*server_encoding
*client_encoding
*is_superuser
*session_authorization
*DateStyle
*TimeZone
*integer_datetimes
*standard_conforming_strings
. -
#pass ⇒ Object
Returns the authenticated password.
-
#pipeline_status ⇒ Integer
Returns the current pipeline mode status of the libpq connection.
-
#pipeline_sync(*args) ⇒ Object
(also: #async_pipeline_sync)
call-seq: conn.pipeline_sync.
-
#port ⇒ Object
Returns the connected server port number.
-
#prepare(stmt_name, sql[, param_types ]) ⇒ PG::Result
(also: #async_prepare)
Prepares statement sql with name name to be executed later.
-
#protocol_version ⇒ Integer
Interrogates the frontend/backend protocol being used.
-
#put_copy_data(buffer, encoder = nil) ⇒ Object
(also: #async_put_copy_data)
call-seq: conn.put_copy_data( buffer [, encoder] ) -> Boolean.
-
#put_copy_end(*args) ⇒ Object
(also: #async_put_copy_end)
call-seq: conn.put_copy_end( [ error_message ] ) -> Boolean.
-
#quote_ident(str_or_array) ⇒ Object
Returns a string that is safe for inclusion in a SQL query as an identifier.
-
#reset ⇒ Object
(also: #async_reset)
call-seq: conn.reset().
-
#reset_poll ⇒ Integer
Checks the status of a connection reset operation.
-
#reset_start ⇒ nil
Initiate a connection reset in a nonblocking manner.
-
#send_describe_portal(portal_name) ⇒ nil
Asynchronously send command to the server.
-
#send_describe_prepared(statement_name) ⇒ nil
Asynchronously send command to the server.
-
#send_flush_request ⇒ nil
Sends a request for the server to flush its output buffer.
-
#send_pipeline_sync ⇒ nil
Marks a synchronization point in a pipeline by sending a sync message without flushing the send buffer.
-
#send_prepare(stmt_name, sql[, param_types ]) ⇒ nil
Prepares statement sql with name name to be executed later.
-
#send_query(sql) ⇒ nil
Sends SQL query request specified by sql to PostgreSQL for asynchronous processing, and immediately returns.
-
#send_query_params(sql, params[, result_format [, type_map ]]) ⇒ nil
Sends SQL query request specified by sql to PostgreSQL for asynchronous processing, and immediately returns.
-
#send_query_prepared(*args) ⇒ Object
Execute prepared named statement specified by statement_name asynchronously, and returns immediately.
-
#server_version ⇒ Integer
Returns an integer representing the server version.
-
#set_chunked_rows_mode ⇒ self
Select chunked mode for the currently-executing query.
-
#set_client_encoding(encoding) ⇒ Object
(also: #async_set_client_encoding, #client_encoding=)
Sets the client encoding to the encoding String.
-
#set_default_encoding ⇒ Encoding
If Ruby has its Encoding.default_internal set, set PostgreSQL’s client_encoding to match.
-
#set_error_context_visibility(context_visibility) ⇒ Integer
Sets connection’s context display mode to context_visibility and returns the previous setting.
-
#set_error_verbosity(verbosity) ⇒ Integer
Sets connection’s verbosity to verbosity and returns the previous setting.
-
#set_notice_processor {|message| ... } ⇒ Proc
See #set_notice_receiver for the description of what this and the notice_processor methods do.
-
#set_notice_receiver {|result| ... } ⇒ Proc
Notice and warning messages generated by the server are not returned by the query execution functions, since they do not imply failure of the query.
-
#set_single_row_mode ⇒ self
To enter single-row mode, call this method immediately after a successful call of send_query (or a sibling function).
-
#setnonblocking(enabled) ⇒ Object
(also: #async_setnonblocking)
call-seq: conn.setnonblocking(Boolean) -> nil.
-
#socket ⇒ Integer
This method is deprecated.
-
#socket_io ⇒ Object
Fetch an IO object created from the Connection’s underlying socket.
-
#ssl_attribute(attribute_name) ⇒ String
Returns SSL-related information about the connection.
-
#ssl_attribute_names ⇒ Array<String>
Return an array of SSL attribute names available.
-
#ssl_attributes ⇒ Object
call-seq: conn.ssl_attributes -> Hash<String,String>.
-
#ssl_in_use? ⇒ Boolean
Returns
true
if the connection uses SSL/TLS,false
if not. -
#status ⇒ Object
Returns the status of the connection, which is one: PG::Constants::CONNECTION_OK PG::Constants::CONNECTION_BAD.
-
#sync_cancel ⇒ Object
PostgreSQL-17+.
-
#sync_close_portal(portal_name) ⇒ PG::Result
This function has the same behavior as #async_close_portal, but is implemented using the synchronous command processing API of libpq.
-
#sync_close_prepared(stmt_name) ⇒ PG::Result
This function has the same behavior as #async_close_prepared, but is implemented using the synchronous command processing API of libpq.
-
#sync_describe_portal(portal_name) ⇒ PG::Result
This function has the same behavior as #async_describe_portal, but is implemented using the synchronous command processing API of libpq.
-
#sync_describe_prepared(statement_name) ⇒ PG::Result
This function has the same behavior as #async_describe_prepared, but is implemented using the synchronous command processing API of libpq.
- #sync_encrypt_password(*args) ⇒ Object
-
#sync_exec(*args) ⇒ Object
This function has the same behavior as #async_exec, but is implemented using the synchronous command processing API of libpq.
-
#sync_exec_params(*args) ⇒ Object
This function has the same behavior as #async_exec_params, but is implemented using the synchronous command processing API of libpq.
-
#sync_exec_prepared(*args) ⇒ Object
This function has the same behavior as #async_exec_prepared, but is implemented using the synchronous command processing API of libpq.
- #sync_flush ⇒ Object
- #sync_get_copy_data(*args) ⇒ Object
-
#sync_get_last_result ⇒ PG::Result
This function has the same behavior as #async_get_last_result, but is implemented using the synchronous command processing API of libpq.
- #sync_get_result ⇒ Object
- #sync_isnonblocking ⇒ Object
-
#sync_pipeline_sync ⇒ nil
This function has the same behavior as #async_pipeline_sync, but is implemented using the synchronous command processing API of libpq.
-
#sync_prepare(stmt_name, sql[, param_types ]) ⇒ PG::Result
This function has the same behavior as #async_prepare, but is implemented using the synchronous command processing API of libpq.
-
#sync_put_copy_data(*args) ⇒ Object
**** PG::Connection INSTANCE METHODS: COPY *****.
- #sync_put_copy_end(*args) ⇒ Object
- #sync_reset ⇒ Object
-
#sync_set_client_encoding(encoding) ⇒ Object
This function has the same behavior as #async_set_client_encoding, but is implemented using the synchronous command processing API of libpq.
- #sync_setnonblocking(state) ⇒ Object
-
#trace(stream) ⇒ nil
Enables tracing message passing between backend.
-
#transaction ⇒ Object
call-seq: conn.transaction { |conn| … } -> result of the block.
-
#transaction_status ⇒ Object
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).
-
#tty ⇒ Object
Obsolete function.
-
#type_map_for_queries ⇒ TypeMap
Returns the default TypeMap that is currently set for type casts of query bind parameters.
-
#type_map_for_queries=(typemap) ⇒ Object
Set the default TypeMap that is used for type casts of query bind parameters.
-
#type_map_for_results ⇒ TypeMap
Returns the default TypeMap that is currently set for type casts of result values.
-
#type_map_for_results=(typemap) ⇒ Object
Set the default TypeMap that is used for type casts of result values.
-
#PG::Connection.unescape_bytea(string) ⇒ Object
Converts an escaped string representation of binary data into binary data — the reverse of #escape_bytea.
-
#untrace ⇒ nil
Disables the message tracing.
-
#user ⇒ Object
Returns the authenticated user name.
-
#wait_for_notify([ timeout ]) {|event, pid, payload| ... } ⇒ String
(also: #notifies_wait)
Blocks while waiting for notification(s), or until the optional timeout is reached, whichever comes first.
Class Method Details
.async_api=(enable) ⇒ Object
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.
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 |
# File 'lib/pg/connection.rb', line 1080 def async_api=(enable) self.async_send_api = enable REDIRECT_METHODS.each do |ali, (async, sync)| remove_method(ali) if method_defined?(ali) alias_method( ali, enable ? async : sync ) end REDIRECT_CLASS_METHODS.each do |ali, (async, sync)| singleton_class.remove_method(ali) if method_defined?(ali) singleton_class.alias_method(ali, enable ? async : sync ) end end |
.async_send_api=(enable) ⇒ Object
1057 1058 1059 1060 1061 1062 |
# File 'lib/pg/connection.rb', line 1057 def async_send_api=(enable) REDIRECT_SEND_METHODS.each do |ali, (async, sync)| undef_method(ali) if method_defined?(ali) alias_method( ali, enable ? async : sync ) end end |
.conndefaults ⇒ Object
call-seq:
PG::Connection.conndefaults() -> Array
Returns an array of hashes. Each hash has the keys:
:keyword
-
the name of the option
:envvar
-
the environment variable to fall back to
:compiled
-
the compiled in option as a secondary fallback
:val
-
the option’s current value, or
nil
if not known :label
-
the label for the field
:dispchar
-
“” for normal, “D” for debug, and “*” for password
:dispsize
-
field size
379 380 381 382 383 384 385 386 387 388 389 390 |
# File 'ext/pg_connection.c', line 379
static VALUE
pgconn_s_conndefaults(VALUE self)
{
PQconninfoOption *options = PQconndefaults();
VALUE array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
UNUSED( self );
return array;
}
|
.conndefaults_hash ⇒ Object
Return the Postgres connection defaults structure as a Hash keyed by option keyword (as a Symbol).
See also #conndefaults
337 338 339 340 341 |
# File 'lib/pg/connection.rb', line 337 def self.conndefaults_hash return self.conndefaults.each_with_object({}) do |info, hash| hash[ info[:keyword].to_sym ] = info[:val] end end |
.connect_hash_to_string(hash) ⇒ Object
Convert Hash options to connection String
Values are properly quoted and escaped.
44 45 46 |
# File 'lib/pg/connection.rb', line 44 def self.connect_hash_to_string( hash ) hash.map { |k,v| "#{k}=#{quote_connstr(v)}" }.join( ' ' ) end |
.PG::Connection.connect_start(connection_hash) ⇒ Object .PG::Connection.connect_start(connection_string) ⇒ Object .PG::Connection.connect_start(host, port, options, tty, dbname, login, password) ⇒ Object
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.
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'ext/pg_connection.c', line 316
static VALUE
pgconn_s_connect_start( int argc, VALUE *argv, VALUE klass )
{
VALUE rb_conn;
VALUE conninfo;
t_pg_connection *this;
/*
* PG::Connection.connect_start must act as both alloc() and initialize()
* because it is not invoked by calling new().
*/
rb_conn = pgconn_s_allocate( klass );
this = pg_get_connection( rb_conn );
conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
this->pgconn = gvl_PQconnectStart( StringValueCStr(conninfo) );
if( this->pgconn == NULL )
rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate PGconn structure");
if ( PQstatus(this->pgconn) == CONNECTION_BAD )
pg_raise_conn_error( rb_eConnectionBad, rb_conn, "%s", PQerrorMessage(this->pgconn));
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn );
}
return rb_conn;
}
|
.conninfo_parse(conninfo) ⇒ Object
call-seq:
PG::Connection.conninfo_parse(conninfo_string) -> Array
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.
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'ext/pg_connection.c', line 402
static VALUE
pgconn_s_conninfo_parse(VALUE self, VALUE conninfo)
{
VALUE array;
char *errmsg = NULL;
PQconninfoOption *options = PQconninfoParse(StringValueCStr(conninfo), &errmsg);
if(errmsg){
VALUE error = rb_str_new_cstr(errmsg);
PQfreemem(errmsg);
rb_raise(rb_ePGerror, "%"PRIsVALUE, error);
}
array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
UNUSED( self );
return array;
}
|
.PG::Connection.encrypt_password(password, username) ⇒ String
This is an older, deprecated version of #encrypt_password. The difference is that this function always uses md5
as the encryption algorithm.
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 |
# File 'ext/pg_connection.c', line 456
static VALUE
pgconn_s_encrypt_password(VALUE self, VALUE password, VALUE username)
{
char *encrypted = NULL;
VALUE rval = Qnil;
UNUSED( self );
Check_Type(password, T_STRING);
Check_Type(username, T_STRING);
encrypted = PQencryptPassword(StringValueCStr(password), StringValueCStr(username));
rval = rb_str_new2( encrypted );
PQfreemem( encrypted );
return rval;
}
|
.escape_bytea(string) ⇒ 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.
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 |
# File 'ext/pg_connection.c', line 1732
static VALUE
pgconn_s_escape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t from_len, to_len;
VALUE ret;
Check_Type(str, T_STRING);
from = (unsigned char*)RSTRING_PTR(str);
from_len = RSTRING_LEN(str);
if ( rb_obj_is_kind_of(self, rb_cPGconn) ) {
to = PQescapeByteaConn(pg_get_pgconn(self), from, from_len, &to_len);
} else {
to = PQescapeBytea( from, from_len, &to_len);
}
ret = rb_str_new((char*)to, to_len - 1);
PQfreemem(to);
return ret;
}
|
.escape_string(str) ⇒ String
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.
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 |
# File 'ext/pg_connection.c', line 1678
static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
size_t size;
int error;
VALUE result;
int enc_idx;
int singleton = !rb_obj_is_kind_of(self, rb_cPGconn);
StringValueCStr(string);
enc_idx = singleton ? ENCODING_GET(string) : pg_get_connection(self)->enc_idx;
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
result = rb_str_new(NULL, RSTRING_LEN(string) * 2 + 1);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
if( !singleton ) {
size = PQescapeStringConn(pg_get_pgconn(self), RSTRING_PTR(result),
RSTRING_PTR(string), RSTRING_LEN(string), &error);
if(error)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(pg_get_pgconn(self)));
} else {
size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
}
rb_str_set_len(result, size);
return result;
}
|
.new(*args) ⇒ Object Also known as: async_connect, connect, open, setdb, setdblogin
call-seq:
PG::Connection.new -> conn
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:[email protected]: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_hosts
is 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
,hostaddr
andport
combination is not tried a second time, even if it’s specified several times. It’s still possible to do load balancing withload_balance_hosts
set torandom
and 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.
870 871 872 873 874 875 876 877 878 879 880 881 |
# File 'lib/pg/connection.rb', line 870 def new(*args) conn = connect_to_hosts(*args) if block_given? begin return yield conn ensure conn.finish end end conn end |
.parse_connect_args(*args) ⇒ Object
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 “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.
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/pg/connection.rb', line 64 def self.parse_connect_args( *args ) hash_arg = args.last.is_a?( Hash ) ? args.pop.transform_keys(&:to_sym) : {} iopts = {} if args.length == 1 case args.first.to_s when /=/, /:\/\// # Option or URL string style conn_string = args.first.to_s iopts = PG::Connection.conninfo_parse(conn_string).each_with_object({}){|h, o| o[h[:keyword].to_sym] = h[:val] if h[:val] } else # Positional parameters (only host given) iopts[CONNECT_ARGUMENT_ORDER.first.to_sym] = args.first end else # Positional parameters with host and more max = CONNECT_ARGUMENT_ORDER.length raise ArgumentError, "Extra positional parameter %d: %p" % [ max + 1, args[max] ] if args.length > max CONNECT_ARGUMENT_ORDER.zip( args ) do |(k,v)| iopts[ k.to_sym ] = v if v end iopts.delete(:tty) # ignore obsolete tty parameter end iopts.merge!( hash_arg ) if !iopts[:fallback_application_name] iopts[:fallback_application_name] = PROGRAM_NAME.sub( /^(.{30}).{4,}(.{30})$/ ){ $1+"..."+$2 } end return connect_hash_to_string(iopts) end |
.ping(*args) ⇒ Object Also known as: async_ping
call-seq:
PG::Connection.ping(connection_hash) -> Integer
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.
985 986 987 988 989 990 991 992 993 |
# File 'lib/pg/connection.rb', line 985 def ping(*args) if Fiber.respond_to?(:scheduler) && Fiber.scheduler # Run PQping in a second thread to avoid blocking of the scheduler. # Unfortunately there's no nonblocking way to run ping. Thread.new { sync_ping(*args) }.value else sync_ping(*args) end end |
.quote_connstr(value) ⇒ Object
Quote a single value
for use in a connection-parameter string.
37 38 39 |
# File 'lib/pg/connection.rb', line 37 def self.quote_connstr( value ) return "'" + value.to_s.gsub( /[\\']/ ) {|m| '\\' + m } + "'" end |
.quote_ident(str) ⇒ 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.
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 |
# File 'ext/pg_connection.c', line 3141
static VALUE
pgconn_s_quote_ident(VALUE self, VALUE str_or_array)
{
VALUE ret;
int enc_idx;
if( rb_obj_is_kind_of(self, rb_cPGconn) ){
enc_idx = pg_get_connection(self)->enc_idx;
}else{
enc_idx = RB_TYPE_P(str_or_array, T_STRING) ? ENCODING_GET( str_or_array ) : rb_ascii8bit_encindex();
}
pg_text_enc_identifier(NULL, str_or_array, NULL, &ret, enc_idx);
return ret;
}
|
.sync_connect(*args) ⇒ Object
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
# File 'ext/pg_connection.c', line 273
static VALUE
pgconn_s_sync_connect(int argc, VALUE *argv, VALUE klass)
{
t_pg_connection *this;
VALUE conninfo;
VALUE self = pgconn_s_allocate( klass );
this = pg_get_connection( self );
conninfo = rb_funcall2( rb_cPGconn, rb_intern("parse_connect_args"), argc, argv );
this->pgconn = gvl_PQconnectdb(StringValueCStr(conninfo));
if(this->pgconn == NULL)
rb_raise(rb_ePGerror, "PQconnectdb() unable to allocate PGconn structure");
if (PQstatus(this->pgconn) == CONNECTION_BAD)
pg_raise_conn_error( rb_eConnectionBad, self, "%s", PQerrorMessage(this->pgconn));
pgconn_set_default_encoding( self );
if (rb_block_given_p()) {
return rb_ensure(rb_yield, self, pgconn_finish, self);
}
return self;
}
|
.sync_ping(*args) ⇒ Object
344 345 346 347 348 349 350 351 352 353 354 |
# File 'ext/pg_connection.c', line 344
static VALUE
pgconn_s_sync_ping( int argc, VALUE *argv, VALUE klass )
{
PGPing ping;
VALUE conninfo;
conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv );
ping = gvl_PQping( StringValueCStr(conninfo) );
return INT2FIX((int)ping);
}
|
.PG::Connection.unescape_bytea(string) ⇒ Object
Converts an escaped string representation of binary data into binary data — the reverse of #escape_bytea. This is needed when retrieving bytea
data in text format, but not when retrieving it in binary format.
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 |
# File 'ext/pg_connection.c', line 1764
static VALUE
pgconn_s_unescape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t to_len;
VALUE ret;
UNUSED( self );
Check_Type(str, T_STRING);
from = (unsigned char*)StringValueCStr(str);
to = PQunescapeBytea(from, &to_len);
ret = rb_str_new((char*)to, to_len);
PQfreemem(to);
return ret;
}
|
Instance Method Details
#backend_key ⇒ Integer
Returns the key of the backend server process for this connection. This key can be used to cancel queries on the server.
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 |
# File 'ext/pg_connection.c', line 1040
static VALUE
pgconn_backend_key(VALUE self)
{
int be_key;
struct pg_cancel *cancel;
PGconn *conn = pg_get_pgconn(self);
cancel = (struct pg_cancel*)PQgetCancel(conn);
if(cancel == NULL)
pg_raise_conn_error( rb_ePGerror, self, "Invalid connection!");
if( cancel->be_pid != PQbackendPID(conn) )
rb_raise(rb_ePGerror,"Unexpected binary struct layout - please file a bug report at ruby-pg!");
be_key = cancel->be_key;
PQfreeCancel(cancel);
return INT2NUM(be_key);
}
|
#backend_pid ⇒ Integer
Returns the process ID of the backend server process for this connection. Note that this is a PID on database server host.
1009 1010 1011 1012 1013 |
# File 'ext/pg_connection.c', line 1009
static VALUE
pgconn_backend_pid(VALUE self)
{
return INT2NUM(PQbackendPID(pg_get_pgconn(self)));
}
|
#block([ timeout ]) ⇒ Boolean
Blocks until the server is no longer busy, or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns false
if timeout is reached, true
otherwise.
If true
is returned, conn.is_busy
will return false
and conn.get_result
will not block.
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 |
# File 'ext/pg_connection.c', line 3178
VALUE
pgconn_block( int argc, VALUE *argv, VALUE self ) {
struct timeval timeout;
struct timeval *ptimeout = NULL;
VALUE timeout_in;
double timeout_sec;
void *ret;
if ( rb_scan_args(argc, argv, "01", &timeout_in) == 1 ) {
timeout_sec = NUM2DBL( timeout_in );
timeout.tv_sec = (time_t)timeout_sec;
timeout.tv_usec = (suseconds_t)((timeout_sec - (long)timeout_sec) * 1e6);
ptimeout = &timeout;
}
ret = wait_socket_readable( self, ptimeout, get_result_readable);
if( !ret )
return Qfalse;
return Qtrue;
}
|
#cancel ⇒ Object Also known as: async_cancel
PostgreSQL < 17
626 627 628 629 630 631 |
# File 'lib/pg/connection.rb', line 626 def cancel cancon = PG::CancelConnection.new(self) cancon.async_cancel rescue PG::Error => err err.to_s end |
#check_socket ⇒ Object
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.
384 385 386 387 388 389 |
# File 'lib/pg/connection.rb', line 384 def check_socket while socket_io.wait_readable(0) consume_input end nil end |
#close_portal(portal_name) ⇒ PG::Result Also known as: async_close_portal
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.
3676 3677 3678 3679 3680 |
# File 'ext/pg_connection.c', line 3676
static VALUE
pgconn_async_close_portal(VALUE self, VALUE portal)
{
return pgconn_async_describe_close_prepared_potral(self, portal, pgconn_send_close_portal);
}
|
#close_prepared(statement_name) ⇒ PG::Result Also known as: async_close_prepared
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.
3652 3653 3654 3655 3656 |
# File 'ext/pg_connection.c', line 3652
static VALUE
pgconn_async_close_prepared(VALUE self, VALUE stmt_name)
{
return pgconn_async_describe_close_prepared_potral(self, stmt_name, pgconn_send_close_prepared);
}
|
#conndefaults ⇒ Object
Returns an array of Hashes with connection defaults. See ::conndefaults for details.
329 330 331 |
# File 'lib/pg/connection.rb', line 329 def conndefaults return self.class.conndefaults end |
#conndefaults_hash ⇒ Object
Returns a Hash with connection defaults. See ::conndefaults_hash for details.
345 346 347 |
# File 'lib/pg/connection.rb', line 345 def conndefaults_hash return self.class.conndefaults_hash end |
#connect_poll ⇒ Integer
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.
514 515 516 517 518 519 520 521 522 523 |
# File 'ext/pg_connection.c', line 514
static VALUE
pgconn_connect_poll(VALUE self)
{
PostgresPollingStatusType status;
pgconn_close_socket_io(self);
status = gvl_PQconnectPoll(pg_get_pgconn(self));
return INT2FIX((int)status);
}
|
#connection_needs_password ⇒ Boolean
Returns true
if the authentication method required a password, but none was available. false
otherwise.
1069 1070 1071 1072 1073 |
# File 'ext/pg_connection.c', line 1069
static VALUE
pgconn_connection_needs_password(VALUE self)
{
return PQconnectionNeedsPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
|
#connection_used_password ⇒ Boolean
Returns true
if the authentication method used a caller-supplied password, false
otherwise.
1082 1083 1084 1085 1086 |
# File 'ext/pg_connection.c', line 1082
static VALUE
pgconn_connection_used_password(VALUE self)
{
return PQconnectionUsedPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
|
#conninfo ⇒ Hash
Returns the connection options used by a live connection.
763 764 765 766 767 768 769 770 771 772 773 |
# File 'ext/pg_connection.c', line 763
static VALUE
pgconn_conninfo( VALUE self )
{
PGconn *conn = pg_get_pgconn(self);
PQconninfoOption *options = PQconninfo( conn );
VALUE array = pgconn_make_conninfo_array( options );
PQconninfoFree(options);
return array;
}
|
#conninfo_hash ⇒ Object
Return the Postgres connection info structure as a Hash keyed by option keyword (as a Symbol).
See also #conninfo
353 354 355 356 357 |
# File 'lib/pg/connection.rb', line 353 def conninfo_hash return self.conninfo.each_with_object({}) do |info, hash| hash[ info[:keyword].to_sym ] = info[:val] end end |
#consume_input ⇒ Object
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.
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 |
# File 'ext/pg_connection.c', line 2272
static VALUE
pgconn_consume_input(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
/* returns 0 on error */
if(PQconsumeInput(conn) == 0) {
pgconn_close_socket_io(self);
pg_raise_conn_error( rb_eConnectionBad, self, "%s", PQerrorMessage(conn));
}
return Qnil;
}
|
#copy_data(sql, coder = nil) ⇒ Object
call-seq:
conn.copy_data( sql [, coder] ) {|sql_result| ... } -> PG::Result
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"]
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
# File 'lib/pg/connection.rb', line 214 def copy_data( sql, coder=nil ) raise PG::NotInBlockingMode.new("copy_data can not be used in nonblocking mode", connection: self) if nonblocking? res = exec( sql ) case res.result_status when PGRES_COPY_IN begin if coder && res.binary_tuples == 1 # Binary file header (11 byte signature, 32 bit flags and 32 bit extension length) put_copy_data(BinarySignature + ("\x00" * 8)) end if coder old_coder = self.encoder_for_put_copy_data self.encoder_for_put_copy_data = coder end yield res rescue Exception => err errmsg = "%s while copy data: %s" % [ err.class.name, err. ] begin put_copy_end( errmsg ) rescue PG::Error # Ignore error in cleanup to avoid losing original exception end discard_results raise err else begin self.encoder_for_put_copy_data = old_coder if coder if coder && res.binary_tuples == 1 put_copy_data("\xFF\xFF") # Binary file trailer 16 bit "-1" end put_copy_end rescue PG::Error => err raise PG::LostCopyState.new("#{err} (probably by executing another SQL query while running a COPY command)", connection: self) end get_last_result ensure self.encoder_for_put_copy_data = old_coder if coder end when PGRES_COPY_OUT begin if coder old_coder = self.decoder_for_get_copy_data self.decoder_for_get_copy_data = coder end yield res rescue Exception cancel discard_results raise else if coder && res.binary_tuples == 1 # There are two end markers in binary mode: file trailer and the final nil. # The file trailer is expected to be processed by BinaryDecoder::CopyRow and already returns nil, so that the remaining NULL from PQgetCopyData is retrieved here: if get_copy_data discard_results raise PG::NotAllCopyDataRetrieved.new("Not all binary COPY data retrieved", connection: self) end end res = get_last_result if !res discard_results raise PG::LostCopyState.new("Lost COPY state (probably by executing another SQL query while running a COPY command)", connection: self) elsif res.result_status != PGRES_COMMAND_OK discard_results raise PG::NotAllCopyDataRetrieved.new("Not all COPY data retrieved", connection: self) end res ensure self.decoder_for_get_copy_data = old_coder if coder end else raise ArgumentError, "SQL command is no COPY statement: #{sql}" end end |
#db ⇒ Object
Returns the connected database name.
632 633 634 635 636 637 638 |
# File 'ext/pg_connection.c', line 632
static VALUE
pgconn_db(VALUE self)
{
char *db = PQdb(pg_get_pgconn(self));
if (!db) return Qnil;
return rb_str_new2(db);
}
|
#decoder_for_get_copy_data ⇒ PG::Coder
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.
4593 4594 4595 4596 4597 4598 4599 |
# File 'ext/pg_connection.c', line 4593
static VALUE
pgconn_decoder_for_get_copy_data_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->decoder_for_get_copy_data;
}
|
#decoder_for_get_copy_data=(decoder) ⇒ Object
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.
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 |
# File 'ext/pg_connection.c', line 4564
static VALUE
pgconn_decoder_for_get_copy_data_set(VALUE self, VALUE decoder)
{
t_pg_connection *this = pg_get_connection( self );
rb_check_frozen(self);
if( decoder != Qnil ){
t_pg_coder *co;
UNUSED(co);
/* Check argument type */
TypedData_Get_Struct(decoder, t_pg_coder, &pg_coder_type, co);
}
RB_OBJ_WRITE(self, &this->decoder_for_get_copy_data, decoder);
return decoder;
}
|
#describe_portal(portal_name) ⇒ PG::Result Also known as: async_describe_portal
Retrieve information about the portal portal_name.
See also corresponding libpq function.
3613 3614 3615 3616 3617 |
# File 'ext/pg_connection.c', line 3613
static VALUE
pgconn_async_describe_portal(VALUE self, VALUE portal)
{
return pgconn_async_describe_close_prepared_potral(self, portal, pgconn_send_describe_portal);
}
|
#describe_prepared(statement_name) ⇒ PG::Result Also known as: async_describe_prepared
Retrieve information about the prepared statement statement_name.
See also corresponding libpq function.
3628 3629 3630 3631 3632 |
# File 'ext/pg_connection.c', line 3628
static VALUE
pgconn_async_describe_prepared(VALUE self, VALUE stmt_name)
{
return pgconn_async_describe_close_prepared_potral(self, stmt_name, pgconn_send_describe_prepared);
}
|
#discard_results ⇒ Object
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:
-
nil
when the connection is already idle -
true
when some results have been discarded -
false
when a failure occurred and the connection was closed
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 |
# File 'ext/pg_connection.c', line 3305
static VALUE
pgconn_discard_results(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
VALUE socket_io;
switch( PQtransactionStatus(conn) ) {
case PQTRANS_IDLE:
case PQTRANS_INTRANS:
case PQTRANS_INERROR:
return Qnil;
default:;
}
socket_io = pgconn_socket_io(self);
for(;;) {
PGresult *cur;
int status;
/* pgconn_block() raises an exception in case of errors.
* To avoid this call pg_rb_io_wait() and PQconsumeInput() without rb_raise().
*/
while( gvl_PQisBusy(conn) ){
int events;
switch( PQflush(conn) ) {
case 1:
events = RB_NUM2INT(pg_rb_io_wait(socket_io, RB_INT2NUM(PG_RUBY_IO_READABLE | PG_RUBY_IO_WRITABLE), Qnil));
if (events & PG_RUBY_IO_READABLE){
if ( PQconsumeInput(conn) == 0 ) goto error;
}
break;
case 0:
pg_rb_io_wait(socket_io, RB_INT2NUM(PG_RUBY_IO_READABLE), Qnil);
if ( PQconsumeInput(conn) == 0 ) goto error;
break;
default:
goto error;
}
}
cur = gvl_PQgetResult(conn);
if( cur == NULL) break;
status = PQresultStatus(cur);
PQclear(cur);
if (status == PGRES_COPY_IN){
while( gvl_PQputCopyEnd(conn, "COPY terminated by new query or discard_results") == 0 ){
pgconn_async_flush(self);
}
}
if (status == PGRES_COPY_OUT){
for(;;) {
char *buffer = NULL;
int st = gvl_PQgetCopyData(conn, &buffer, 1);
if( st == 0 ) {
/* would block -> wait for readable data */
pg_rb_io_wait(socket_io, RB_INT2NUM(PG_RUBY_IO_READABLE), Qnil);
if ( PQconsumeInput(conn) == 0 ) goto error;
} else if( st > 0 ) {
/* some data retrieved -> discard it */
PQfreemem(buffer);
} else {
/* no more data */
break;
}
}
}
}
return Qtrue;
error:
pgconn_close_socket_io(self);
return Qfalse;
}
|
#encoder_for_put_copy_data ⇒ PG::Coder
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.
4544 4545 4546 4547 4548 4549 4550 |
# File 'ext/pg_connection.c', line 4544
static VALUE
pgconn_encoder_for_put_copy_data_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->encoder_for_put_copy_data;
}
|
#encoder_for_put_copy_data=(encoder) ⇒ Object
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.
4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 |
# File 'ext/pg_connection.c', line 4515
static VALUE
pgconn_encoder_for_put_copy_data_set(VALUE self, VALUE encoder)
{
t_pg_connection *this = pg_get_connection( self );
rb_check_frozen(self);
if( encoder != Qnil ){
t_pg_coder *co;
UNUSED(co);
/* Check argument type */
TypedData_Get_Struct(encoder, t_pg_coder, &pg_coder_type, co);
}
RB_OBJ_WRITE(self, &this->encoder_for_put_copy_data, encoder);
return encoder;
}
|
#encrypt_password(password, username, algorithm = nil) ⇒ Object Also known as: async_encrypt_password
call-seq:
conn.encrypt_password( password, username, algorithm=nil ) -> 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.
579 580 581 582 |
# File 'lib/pg/connection.rb', line 579 def encrypt_password( password, username, algorithm=nil ) algorithm ||= exec("SHOW password_encryption").getvalue(0,0) sync_encrypt_password(password, username, algorithm) end |
#enter_pipeline_mode ⇒ nil
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
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 |
# File 'ext/pg_connection.c', line 3793
static VALUE
pgconn_enter_pipeline_mode(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = PQenterPipelineMode(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
|
#error_message ⇒ String
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.
905 906 907 908 909 910 911 |
# File 'ext/pg_connection.c', line 905
static VALUE
pgconn_error_message(VALUE self)
{
char *error = PQerrorMessage(pg_get_pgconn(self));
if (!error) return Qnil;
return rb_str_new2(error);
}
|
#escape_bytea(string) ⇒ 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.
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 |
# File 'ext/pg_connection.c', line 1732
static VALUE
pgconn_s_escape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t from_len, to_len;
VALUE ret;
Check_Type(str, T_STRING);
from = (unsigned char*)RSTRING_PTR(str);
from_len = RSTRING_LEN(str);
if ( rb_obj_is_kind_of(self, rb_cPGconn) ) {
to = PQescapeByteaConn(pg_get_pgconn(self), from, from_len, &to_len);
} else {
to = PQescapeBytea( from, from_len, &to_len);
}
ret = rb_str_new((char*)to, to_len - 1);
PQfreemem(to);
return ret;
}
|
#escape_identifier(str) ⇒ String
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.
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 |
# File 'ext/pg_connection.c', line 1825
static VALUE
pgconn_escape_identifier(VALUE self, VALUE string)
{
t_pg_connection *this = pg_get_connection_safe( self );
char *escaped = NULL;
VALUE result = Qnil;
int enc_idx = this->enc_idx;
StringValueCStr(string);
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
escaped = PQescapeIdentifier(this->pgconn, RSTRING_PTR(string), RSTRING_LEN(string));
if (escaped == NULL)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
result = rb_str_new2(escaped);
PQfreemem(escaped);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
return result;
}
|
#escape_literal(str) ⇒ String
Escape an arbitrary String str
as a literal.
See also PG::TextEncoder::QuotedLiteral for a type cast integrated version of this function.
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 |
# File 'ext/pg_connection.c', line 1791
static VALUE
pgconn_escape_literal(VALUE self, VALUE string)
{
t_pg_connection *this = pg_get_connection_safe( self );
char *escaped = NULL;
VALUE result = Qnil;
int enc_idx = this->enc_idx;
StringValueCStr(string);
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
escaped = PQescapeLiteral(this->pgconn, RSTRING_PTR(string), RSTRING_LEN(string));
if (escaped == NULL)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
result = rb_str_new2(escaped);
PQfreemem(escaped);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
return result;
}
|
#escape_string(str) ⇒ String Also known as: escape
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.
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 |
# File 'ext/pg_connection.c', line 1678
static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
size_t size;
int error;
VALUE result;
int enc_idx;
int singleton = !rb_obj_is_kind_of(self, rb_cPGconn);
StringValueCStr(string);
enc_idx = singleton ? ENCODING_GET(string) : pg_get_connection(self)->enc_idx;
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
result = rb_str_new(NULL, RSTRING_LEN(string) * 2 + 1);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
if( !singleton ) {
size = PQescapeStringConn(pg_get_pgconn(self), RSTRING_PTR(result),
RSTRING_PTR(string), RSTRING_LEN(string), &error);
if(error)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(pg_get_pgconn(self)));
} else {
size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
}
rb_str_set_len(result, size);
return result;
}
|
#exec(sql) ⇒ PG::Result #exec(sql) {|pg_result| ... } ⇒ Object Also known as: async_exec
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.
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 |
# File 'ext/pg_connection.c', line 3411
static VALUE
pgconn_async_exec(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_query( argc, argv, self );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
|
#exec_params(sql, params[, result_format [, type_map ]]) ⇒ nil #exec_params(sql, params[, result_format [, type_map ]]) {|pg_result| ... } ⇒ Object Also known as: async_exec_params
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.
3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 |
# File 'ext/pg_connection.c', line 3477
static VALUE
pgconn_async_exec_params(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
/* If called with no or nil parameters, use PQsendQuery for compatibility */
if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
pg_deprecated(3, ("forwarding async_exec_params to async_exec is deprecated"));
pgconn_send_query( argc, argv, self );
} else {
pgconn_send_query_params( argc, argv, self );
}
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
|
#exec_prepared(statement_name[, params, result_format[, type_map]]) ⇒ PG::Result #exec_prepared(statement_name[, params, result_format[, type_map]]) {|pg_result| ... } ⇒ Object Also known as: async_exec_prepared
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.
3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 |
# File 'ext/pg_connection.c', line 3574
static VALUE
pgconn_async_exec_prepared(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_query_prepared( argc, argv, self );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
|
#exit_pipeline_mode ⇒ nil
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
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 |
# File 'ext/pg_connection.c', line 3815
static VALUE
pgconn_exit_pipeline_mode(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = PQexitPipelineMode(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
|
#external_encoding ⇒ Encoding
Return the server_encoding
of the connected database as a Ruby Encoding object. The SQL_ASCII
encoding is mapped to to ASCII_8BIT
.
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 |
# File 'ext/pg_connection.c', line 4326
static VALUE
pgconn_external_encoding(VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
rb_encoding *enc = NULL;
const char *pg_encname = NULL;
pg_encname = PQparameterStatus( this->pgconn, "server_encoding" );
enc = pg_get_pg_encname_as_rb_encoding( pg_encname );
return rb_enc_from_encoding( enc );
}
|
#field_name_type ⇒ Symbol
Get type of field names.
See description at #field_name_type=
4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 |
# File 'ext/pg_connection.c', line 4640
static VALUE
pgconn_field_name_type_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
if( this->flags & PG_RESULT_FIELD_NAMES_SYMBOL ){
return sym_symbol;
} else if( this->flags & PG_RESULT_FIELD_NAMES_STATIC_SYMBOL ){
return sym_static_symbol;
} else {
return sym_string;
}
}
|
#field_name_type=(Symbol) ⇒ Object
Set default type of field names of results retrieved by this connection. It can be set to one of:
-
:string
to use String based field names -
:symbol
to 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=
4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 |
# File 'ext/pg_connection.c', line 4617
static VALUE
pgconn_field_name_type_set(VALUE self, VALUE sym)
{
t_pg_connection *this = pg_get_connection( self );
rb_check_frozen(self);
this->flags &= ~PG_RESULT_FIELD_NAMES_MASK;
if( sym == sym_symbol ) this->flags |= PG_RESULT_FIELD_NAMES_SYMBOL;
else if ( sym == sym_static_symbol ) this->flags |= PG_RESULT_FIELD_NAMES_STATIC_SYMBOL;
else if ( sym == sym_string );
else rb_raise(rb_eArgError, "invalid argument %+"PRIsVALUE, sym);
return sym;
}
|
#finish ⇒ Object Also known as: close
Closes the backend connection.
531 532 533 534 535 536 537 538 539 540 |
# File 'ext/pg_connection.c', line 531
static VALUE
pgconn_finish( VALUE self )
{
t_pg_connection *this = pg_get_connection_safe( self );
pgconn_close_socket_io( self );
PQfinish( this->pgconn );
this->pgconn = NULL;
return Qnil;
}
|
#finished? ⇒ Boolean
Returns true
if the backend connection has been closed.
549 550 551 552 553 554 555 |
# File 'ext/pg_connection.c', line 549
static VALUE
pgconn_finished_p( VALUE self )
{
t_pg_connection *this = pg_get_connection( self );
if ( this->pgconn ) return Qfalse;
return Qtrue;
}
|
#flush ⇒ Boolean Also known as: async_flush
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.
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 |
# File 'ext/pg_connection.c', line 2603
static VALUE
pgconn_async_flush(VALUE self)
{
while( pgconn_sync_flush(self) == Qfalse ){
/* wait for the socket to become read- or write-ready */
int events;
VALUE socket_io = pgconn_socket_io(self);
events = RB_NUM2INT(pg_rb_io_wait(socket_io, RB_INT2NUM(PG_RUBY_IO_READABLE | PG_RUBY_IO_WRITABLE), Qnil));
if (events & PG_RUBY_IO_READABLE){
pgconn_consume_input(self);
}
}
return Qtrue;
}
|
#get_client_encoding ⇒ String
Returns the client encoding as a String.
3072 3073 3074 3075 3076 3077 |
# File 'ext/pg_connection.c', line 3072
static VALUE
pgconn_get_client_encoding(VALUE self)
{
char *encoding = (char *)pg_encoding_to_char(PQclientEncoding(pg_get_pgconn(self)));
return rb_str_new2(encoding);
}
|
#get_copy_data(async = false, decoder = nil) ⇒ Object Also known as: async_get_copy_data
call-seq:
conn.get_copy_data( [ nonblock = false [, decoder = nil ]] ) -> Object
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.
428 429 430 431 432 433 434 435 436 437 438 |
# File 'lib/pg/connection.rb', line 428 def get_copy_data(async=false, decoder=nil) if async return sync_get_copy_data(async, decoder) else while (res=sync_get_copy_data(true, decoder)) == false socket_io.wait_readable consume_input end return res end end |
#get_last_result ⇒ PG::Result Also known as: async_get_last_result
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.
3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 |
# File 'ext/pg_connection.c', line 3255
static VALUE
pgconn_async_get_last_result(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
VALUE rb_pgresult = Qnil;
PGresult *cur, *prev;
cur = prev = NULL;
for(;;) {
int status;
/* Wait for input before reading each result.
* That way we support the ruby-3.x IO scheduler and don't block other ruby threads.
*/
wait_socket_readable(self, NULL, get_result_readable);
cur = gvl_PQgetResult(conn);
if (cur == NULL)
break;
if (prev) PQclear(prev);
prev = cur;
status = PQresultStatus(cur);
if (status == PGRES_COPY_OUT || status == PGRES_COPY_IN || status == PGRES_COPY_BOTH)
break;
}
if (prev) {
rb_pgresult = pg_new_result( prev, self );
pg_result_check(rb_pgresult);
}
return rb_pgresult;
}
|
#get_result ⇒ Object Also known as: async_get_result
call-seq:
conn.get_result() -> PG::Result
conn.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.
405 406 407 408 |
# File 'lib/pg/connection.rb', line 405 def get_result block sync_get_result end |
#host ⇒ Object
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 .
685 686 687 688 689 690 691 |
# File 'ext/pg_connection.c', line 685
static VALUE
pgconn_host(VALUE self)
{
char *host = PQhost(pg_get_pgconn(self));
if (!host) return Qnil;
return rb_str_new2(host);
}
|
#hostaddr ⇒ Object
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.
704 705 706 707 708 709 710 |
# File 'ext/pg_connection.c', line 704
static VALUE
pgconn_hostaddr(VALUE self)
{
char *host = PQhostaddr(pg_get_pgconn(self));
if (!host) return Qnil;
return rb_str_new2(host);
}
|
#inspect ⇒ Object
Return a String representation of the object suitable for debugging.
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/pg/connection.rb', line 100 def inspect str = self.to_s str[-1,0] = if finished? " finished" else stats = [] stats << " status=#{ PG.constants.grep(/CONNECTION_/).find{|c| PG.const_get(c) == status} }" if status != CONNECTION_OK stats << " transaction_status=#{ PG.constants.grep(/PQTRANS_/).find{|c| PG.const_get(c) == transaction_status} }" if transaction_status != PG::PQTRANS_IDLE stats << " nonblocking=#{ isnonblocking }" if isnonblocking stats << " pipeline_status=#{ PG.constants.grep(/PQ_PIPELINE_/).find{|c| PG.const_get(c) == pipeline_status} }" if respond_to?(:pipeline_status) && pipeline_status != PG::PQ_PIPELINE_OFF stats << " client_encoding=#{ get_client_encoding }" if get_client_encoding != "UTF8" stats << " type_map_for_results=#{ type_map_for_results.to_s }" unless type_map_for_results.is_a?(PG::TypeMapAllStrings) stats << " type_map_for_queries=#{ type_map_for_queries.to_s }" unless type_map_for_queries.is_a?(PG::TypeMapAllStrings) stats << " encoder_for_put_copy_data=#{ encoder_for_put_copy_data.to_s }" if encoder_for_put_copy_data stats << " decoder_for_get_copy_data=#{ decoder_for_get_copy_data.to_s }" if decoder_for_get_copy_data " host=#{host} port=#{port} user=#{user}#{stats.join}" end return str end |
#internal_encoding ⇒ Encoding
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’
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 |
# File 'ext/pg_connection.c', line 4264
static VALUE
pgconn_internal_encoding(VALUE self)
{
PGconn *conn = pg_get_pgconn( self );
rb_encoding *enc = pg_conn_enc_get( conn );
if ( enc ) {
return rb_enc_from_encoding( enc );
} else {
return Qnil;
}
}
|
#internal_encoding=(value) ⇒ Object
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.
4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 |
# File 'ext/pg_connection.c', line 4291
static VALUE
pgconn_internal_encoding_set(VALUE self, VALUE enc)
{
rb_check_frozen(self);
if (NIL_P(enc)) {
pgconn_sync_set_client_encoding( self, rb_usascii_str_new_cstr("SQL_ASCII") );
return enc;
}
else if ( TYPE(enc) == T_STRING && strcasecmp("JOHAB", StringValueCStr(enc)) == 0 ) {
pgconn_sync_set_client_encoding(self, rb_usascii_str_new_cstr("JOHAB"));
return enc;
}
else {
rb_encoding *rbenc = rb_to_encoding( enc );
const char *name = pg_get_rb_encoding_as_pg_encoding( rbenc );
if ( gvl_PQsetClientEncoding(pg_get_pgconn( self ), name) == -1 ) {
VALUE server_encoding = pgconn_external_encoding( self );
rb_raise( rb_eEncCompatError, "incompatible character encodings: %s and %s",
rb_enc_name(rb_to_encoding(server_encoding)), name );
}
pgconn_set_internal_encoding_index( self );
return enc;
}
}
|
#is_busy ⇒ Boolean
Returns true
if a command is busy, that is, if #get_result would block. Otherwise returns false
.
2292 2293 2294 2295 2296 |
# File 'ext/pg_connection.c', line 2292
static VALUE
pgconn_is_busy(VALUE self)
{
return gvl_PQisBusy(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
|
#isnonblocking ⇒ Object Also known as: async_isnonblocking, nonblocking?
call-seq:
conn.isnonblocking() -> Boolean
Returns the blocking status of the database connection. Returns true
if the connection is set to nonblocking mode and false
if blocking.
476 477 478 |
# File 'lib/pg/connection.rb', line 476 def isnonblocking false end |
#lo_close(lo_desc) ⇒ nil Also known as: loclose
Closes the postgres large object of lo_desc.
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 |
# File 'ext/pg_connection.c', line 4202
static VALUE
pgconn_loclose(VALUE self, VALUE in_lo_desc)
{
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
int ret;
BLOCKING_BEGIN(conn)
ret = lo_close(conn,lo_desc);
BLOCKING_END(conn)
if(ret < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_close failed");
return Qnil;
}
|
#lo_creat([mode]) ⇒ Integer Also known as: locreat
Creates a large object with mode mode. Returns a large object Oid. On failure, it raises PG::Error.
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 |
# File 'ext/pg_connection.c', line 3919
static VALUE
pgconn_locreat(int argc, VALUE *argv, VALUE self)
{
Oid lo_oid;
int mode;
VALUE nmode;
PGconn *conn = pg_get_pgconn(self);
if (rb_scan_args(argc, argv, "01", &nmode) == 0)
mode = INV_READ;
else
mode = NUM2INT(nmode);
BLOCKING_BEGIN(conn)
lo_oid = lo_creat(conn, mode);
BLOCKING_END(conn)
if (lo_oid == 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_creat failed");
return UINT2NUM(lo_oid);
}
|
#lo_create(oid) ⇒ Integer Also known as: locreate
Creates a large object with oid oid. Returns the large object Oid. On failure, it raises PG::Error.
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 |
# File 'ext/pg_connection.c', line 3949
static VALUE
pgconn_locreate(VALUE self, VALUE in_lo_oid)
{
Oid ret, lo_oid;
PGconn *conn = pg_get_pgconn(self);
lo_oid = NUM2UINT(in_lo_oid);
ret = lo_create(conn, lo_oid);
if (ret == InvalidOid)
pg_raise_conn_error( rb_ePGerror, self, "lo_create failed");
return UINT2NUM(ret);
}
|
#lo_export(oid, file) ⇒ nil Also known as: loexport
Saves a large object of oid to a file.
3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 |
# File 'ext/pg_connection.c', line 3996
static VALUE
pgconn_loexport(VALUE self, VALUE lo_oid, VALUE filename)
{
PGconn *conn = pg_get_pgconn(self);
Oid oid;
int ret;
Check_Type(filename, T_STRING);
oid = NUM2UINT(lo_oid);
BLOCKING_BEGIN(conn)
ret = lo_export(conn, oid, StringValueCStr(filename));
BLOCKING_END(conn)
if (ret < 0) {
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
}
return Qnil;
}
|
#lo_import(file) ⇒ Integer Also known as: loimport
Import a file to a large object. Returns a large object Oid.
On failure, it raises a PG::Error.
3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 |
# File 'ext/pg_connection.c', line 3971
static VALUE
pgconn_loimport(VALUE self, VALUE filename)
{
Oid lo_oid;
PGconn *conn = pg_get_pgconn(self);
Check_Type(filename, T_STRING);
BLOCKING_BEGIN(conn)
lo_oid = lo_import(conn, StringValueCStr(filename));
BLOCKING_END(conn)
if (lo_oid == 0) {
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
}
return UINT2NUM(lo_oid);
}
|
#lo_lseek(lo_desc, offset, whence) ⇒ Integer Also known as: lolseek, lo_seek, loseek
Move the large object pointer lo_desc to offset offset. Valid values for whence are SEEK_SET
, SEEK_CUR
, and SEEK_END
. (Or 0, 1, or 2.)
4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 |
# File 'ext/pg_connection.c', line 4131
static VALUE
pgconn_lolseek(VALUE self, VALUE in_lo_desc, VALUE offset, VALUE whence)
{
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
int ret;
BLOCKING_BEGIN(conn)
ret = lo_lseek(conn, lo_desc, NUM2INT(offset), NUM2INT(whence));
BLOCKING_END(conn)
if(ret < 0) {
pg_raise_conn_error( rb_ePGerror, self, "lo_lseek failed");
}
return INT2FIX(ret);
}
|
#lo_open(oid, [mode]) ⇒ Integer Also known as: loopen
Open a large object of oid. Returns a large object descriptor instance on success. The mode argument specifies the mode for the opened large object,which is either INV_READ
, or INV_WRITE
.
If mode is omitted, the default is INV_READ
.
4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 |
# File 'ext/pg_connection.c', line 4026
static VALUE
pgconn_loopen(int argc, VALUE *argv, VALUE self)
{
Oid lo_oid;
int fd, mode;
VALUE nmode, selfid;
PGconn *conn = pg_get_pgconn(self);
rb_scan_args(argc, argv, "11", &selfid, &nmode);
lo_oid = NUM2UINT(selfid);
if(NIL_P(nmode))
mode = INV_READ;
else
mode = NUM2INT(nmode);
BLOCKING_BEGIN(conn)
fd = lo_open(conn, lo_oid, mode);
BLOCKING_END(conn)
if(fd < 0) {
pg_raise_conn_error( rb_ePGerror, self, "can't open large object: %s", PQerrorMessage(conn));
}
return INT2FIX(fd);
}
|
#lo_read(lo_desc, len) ⇒ String Also known as: loread
Attempts to read len bytes from large object lo_desc, returns resulting data.
4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 |
# File 'ext/pg_connection.c', line 4089
static VALUE
pgconn_loread(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
int ret;
PGconn *conn = pg_get_pgconn(self);
int len = NUM2INT(in_len);
int lo_desc = NUM2INT(in_lo_desc);
VALUE str;
char *buffer;
if (len < 0)
pg_raise_conn_error( rb_ePGerror, self, "negative length %d given", len);
buffer = ALLOC_N(char, len);
BLOCKING_BEGIN(conn)
ret = lo_read(conn, lo_desc, buffer, len);
BLOCKING_END(conn)
if(ret < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_read failed");
if(ret == 0) {
xfree(buffer);
return Qnil;
}
str = rb_str_new(buffer, ret);
xfree(buffer);
return str;
}
|
#lo_tell(lo_desc) ⇒ Integer Also known as: lotell
Returns the current position of the large object lo_desc.
4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 |
# File 'ext/pg_connection.c', line 4155
static VALUE
pgconn_lotell(VALUE self, VALUE in_lo_desc)
{
int position;
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
BLOCKING_BEGIN(conn)
position = lo_tell(conn, lo_desc);
BLOCKING_END(conn)
if(position < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_tell failed");
return INT2FIX(position);
}
|
#lo_truncate(lo_desc, len) ⇒ nil Also known as: lotruncate
Truncates the large object lo_desc to size len.
4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 |
# File 'ext/pg_connection.c', line 4178
static VALUE
pgconn_lotruncate(VALUE self, VALUE in_lo_desc, VALUE in_len)
{
PGconn *conn = pg_get_pgconn(self);
int lo_desc = NUM2INT(in_lo_desc);
size_t len = NUM2INT(in_len);
int ret;
BLOCKING_BEGIN(conn)
ret = lo_truncate(conn,lo_desc,len);
BLOCKING_END(conn)
if(ret < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_truncate failed");
return Qnil;
}
|
#lo_unlink(oid) ⇒ nil Also known as: lounlink
Unlinks (deletes) the postgres large object of oid.
4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 |
# File 'ext/pg_connection.c', line 4225
static VALUE
pgconn_lounlink(VALUE self, VALUE in_oid)
{
PGconn *conn = pg_get_pgconn(self);
Oid oid = NUM2UINT(in_oid);
int ret;
BLOCKING_BEGIN(conn)
ret = lo_unlink(conn,oid);
BLOCKING_END(conn)
if(ret < 0)
pg_raise_conn_error( rb_ePGerror, self, "lo_unlink failed");
return Qnil;
}
|
#lo_write(lo_desc, buffer) ⇒ Integer Also known as: lowrite
Writes the string buffer to the large object lo_desc. Returns the number of bytes written.
4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 |
# File 'ext/pg_connection.c', line 4058
static VALUE
pgconn_lowrite(VALUE self, VALUE in_lo_desc, VALUE buffer)
{
int n;
PGconn *conn = pg_get_pgconn(self);
int fd = NUM2INT(in_lo_desc);
Check_Type(buffer, T_STRING);
if( RSTRING_LEN(buffer) < 0) {
pg_raise_conn_error( rb_ePGerror, self, "write buffer zero string");
}
BLOCKING_BEGIN(conn)
n = lo_write(conn, fd, StringValuePtr(buffer),
RSTRING_LEN(buffer));
BLOCKING_END(conn)
if(n < 0) {
pg_raise_conn_error( rb_ePGerror, self, "lo_write failed: %s", PQerrorMessage(conn));
}
return INT2FIX(n);
}
|
#make_empty_pgresult(status) ⇒ PG::Result
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
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 |
# File 'ext/pg_connection.c', line 1644
static VALUE
pgconn_make_empty_pgresult(VALUE self, VALUE status)
{
PGresult *result;
VALUE rb_pgresult;
PGconn *conn = pg_get_pgconn(self);
result = PQmakeEmptyPGresult(conn, NUM2INT(status));
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
return rb_pgresult;
}
|
#notifies ⇒ Object
Returns a hash of the unprocessed notifications. If there is no unprocessed notifier, it returns nil
.
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 |
# File 'ext/pg_connection.c', line 2367
static VALUE
pgconn_notifies(VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGnotify *notification;
VALUE hash;
VALUE sym_relname, sym_be_pid, sym_extra;
VALUE relname, be_pid, extra;
sym_relname = ID2SYM(rb_intern("relname"));
sym_be_pid = ID2SYM(rb_intern("be_pid"));
sym_extra = ID2SYM(rb_intern("extra"));
notification = gvl_PQnotifies(this->pgconn);
if (notification == NULL) {
return Qnil;
}
hash = rb_hash_new();
relname = rb_str_new2(notification->relname);
be_pid = INT2NUM(notification->be_pid);
extra = rb_str_new2(notification->extra);
PG_ENCODING_SET_NOCHECK( relname, this->enc_idx );
PG_ENCODING_SET_NOCHECK( extra, this->enc_idx );
rb_hash_aset(hash, sym_relname, relname);
rb_hash_aset(hash, sym_be_pid, be_pid);
rb_hash_aset(hash, sym_extra, extra);
PQfreemem(notification);
return hash;
}
|
#options ⇒ Object
Returns backend option string.
747 748 749 750 751 752 753 |
# File 'ext/pg_connection.c', line 747
static VALUE
pgconn_options(VALUE self)
{
char *options = PQoptions(pg_get_pgconn(self));
if (!options) return Qnil;
return rb_str_new2(options);
}
|
#parameter_status(param_name) ⇒ String
Returns the setting of parameter param_name, where param_name is one of
-
server_version
-
server_encoding
-
client_encoding
-
is_superuser
-
session_authorization
-
DateStyle
-
TimeZone
-
integer_datetimes
-
standard_conforming_strings
Returns nil if the value of the parameter is not known.
834 835 836 837 838 839 840 841 842 |
# File 'ext/pg_connection.c', line 834
static VALUE
pgconn_parameter_status(VALUE self, VALUE param_name)
{
const char *ret = PQparameterStatus(pg_get_pgconn(self), StringValueCStr(param_name));
if(ret == NULL)
return Qnil;
else
return rb_str_new2(ret);
}
|
#pass ⇒ Object
Returns the authenticated password.
660 661 662 663 664 665 666 |
# File 'ext/pg_connection.c', line 660
static VALUE
pgconn_pass(VALUE self)
{
char *user = PQpass(pg_get_pgconn(self));
if (!user) return Qnil;
return rb_str_new2(user);
}
|
#pipeline_status ⇒ Integer
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
3772 3773 3774 3775 3776 3777 |
# File 'ext/pg_connection.c', line 3772
static VALUE
pgconn_pipeline_status(VALUE self)
{
int res = PQpipelineStatus(pg_get_pgconn(self));
return INT2FIX(res);
}
|
#pipeline_sync(*args) ⇒ Object Also known as: async_pipeline_sync
call-seq:
conn.pipeline_sync
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.
See enter_pipeline_mode
Raises PG::Error if the connection is not in pipeline mode or sending a sync message failed.
Available since PostgreSQL-14
551 552 553 554 |
# File 'lib/pg/connection.rb', line 551 def pipeline_sync(*args) send_pipeline_sync(*args) flush end |
#port ⇒ Object
Returns the connected server port number.
719 720 721 722 723 724 725 726 727 |
# File 'ext/pg_connection.c', line 719
static VALUE
pgconn_port(VALUE self)
{
char* port = PQport(pg_get_pgconn(self));
if (!port || port[0] == '\0')
return INT2NUM(DEF_PGPORT);
else
return INT2NUM(atoi(port));
}
|
#prepare(stmt_name, sql[, param_types ]) ⇒ PG::Result Also known as: async_prepare
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.
3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 |
# File 'ext/pg_connection.c', line 3521
static VALUE
pgconn_async_prepare(int argc, VALUE *argv, VALUE self)
{
VALUE rb_pgresult = Qnil;
pgconn_discard_results( self );
pgconn_send_prepare( argc, argv, self );
rb_pgresult = pgconn_async_get_last_result( self );
if ( rb_block_given_p() ) {
return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult );
}
return rb_pgresult;
}
|
#protocol_version ⇒ Integer
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.
857 858 859 860 861 862 863 864 865 |
# File 'ext/pg_connection.c', line 857
static VALUE
pgconn_protocol_version(VALUE self)
{
int protocol_version = PQprotocolVersion(pg_get_pgconn(self));
if (protocol_version == 0) {
pg_raise_conn_error( rb_eConnectionBad, self, "PQprotocolVersion() can't get protocol version");
}
return INT2NUM(protocol_version);
}
|
#put_copy_data(buffer, encoder = nil) ⇒ Object Also known as: async_put_copy_data
call-seq:
conn.put_copy_data( buffer [, encoder] ) -> Boolean
Transmits buffer as copy data to the server. Returns true if the data was sent, false if it was not sent (false is only possible if the connection is in nonblocking mode, and this command would block).
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.
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/pg/connection.rb', line 500 def put_copy_data(buffer, encoder=nil) # sync_put_copy_data does a non-blocking attempt to flush data. until res=sync_put_copy_data(buffer, encoder) # It didn't flush immediately and allocation of more buffering memory failed. # Wait for all data sent by doing a blocking flush. res = flush end # And do a blocking flush every 100 calls. # This is to avoid memory bloat, when sending the data is slower than calls to put_copy_data happen. if (@calls_to_put_copy_data += 1) > 100 @calls_to_put_copy_data = 0 res = flush end res end |
#put_copy_end(*args) ⇒ Object Also known as: async_put_copy_end
call-seq:
conn.put_copy_end( [ error_message ] ) -> Boolean
Sends end-of-data indication to the server.
error_message is an optional parameter, and if set, forces the COPY command to fail with the string error_message.
Returns true if the end-of-data was sent, #false* if it was not sent (false is only possible if the connection is in nonblocking mode, and this command would block).
530 531 532 533 534 535 536 |
# File 'lib/pg/connection.rb', line 530 def put_copy_end(*args) until sync_put_copy_end(*args) flush end @calls_to_put_copy_data = 0 flush end |
#quote_ident(str) ⇒ 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.
3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 |
# File 'ext/pg_connection.c', line 3141
static VALUE
pgconn_s_quote_ident(VALUE self, VALUE str_or_array)
{
VALUE ret;
int enc_idx;
if( rb_obj_is_kind_of(self, rb_cPGconn) ){
enc_idx = pg_get_connection(self)->enc_idx;
}else{
enc_idx = RB_TYPE_P(str_or_array, T_STRING) ? ENCODING_GET( str_or_array ) : rb_ascii8bit_encindex();
}
pg_text_enc_identifier(NULL, str_or_array, NULL, &ret, enc_idx);
return ret;
}
|
#reset ⇒ Object Also known as: async_reset
call-seq:
conn.reset()
Resets the backend connection. This method closes the backend connection and tries to re-connect.
591 592 593 594 595 596 597 598 599 600 601 602 |
# File 'lib/pg/connection.rb', line 591 def reset # Use connection options from PG::Connection.new to reconnect with the same options but with renewed DNS resolution. # Use conninfo_hash as a fallback when connect_start was used to create the connection object. iopts = @iopts_for_reset || conninfo_hash.compact if iopts[:host] && !iopts[:host].empty? && PG.library_version >= 100000 iopts = self.class.send(:resolve_hosts, iopts) end conninfo = self.class.parse_connect_args( iopts ); reset_start2(conninfo) async_connect_or_reset(:reset_poll) self end |
#reset_poll ⇒ Integer
Checks the status of a connection reset operation. See Connection.connect_start and #connect_poll for usage information and return values.
614 615 616 617 618 619 620 621 622 623 |
# File 'ext/pg_connection.c', line 614
static VALUE
pgconn_reset_poll(VALUE self)
{
PostgresPollingStatusType status;
pgconn_close_socket_io(self);
status = gvl_PQresetPoll(pg_get_pgconn(self));
return INT2FIX((int)status);
}
|
#reset_start ⇒ nil
Initiate a connection reset in a nonblocking manner. This will close the current connection and attempt to reconnect using the same connection parameters. Use #reset_poll to check the status of the connection reset.
597 598 599 600 601 602 603 604 |
# File 'ext/pg_connection.c', line 597
static VALUE
pgconn_reset_start(VALUE self)
{
pgconn_close_socket_io( self );
if(gvl_PQresetStart(pg_get_pgconn(self)) == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "reset has failed");
return Qnil;
}
|
#send_describe_portal(portal_name) ⇒ nil
Asynchronously send command to the server. Does not block. Use in combination with conn.get_result
.
2201 2202 2203 2204 2205 2206 2207 |
# File 'ext/pg_connection.c', line 2201
static VALUE
pgconn_send_describe_portal(VALUE self, VALUE portal)
{
return pgconn_send_describe_close_prepared_portal(
self, portal, gvl_PQsendDescribePortal,
"PQsendDescribePortal");
}
|
#send_describe_prepared(statement_name) ⇒ nil
Asynchronously send command to the server. Does not block. Use in combination with conn.get_result
.
2185 2186 2187 2188 2189 2190 2191 |
# File 'ext/pg_connection.c', line 2185
static VALUE
pgconn_send_describe_prepared(VALUE self, VALUE stmt_name)
{
return pgconn_send_describe_close_prepared_portal(
self, stmt_name, gvl_PQsendDescribePrepared,
"PQsendDescribePrepared");
}
|
#send_flush_request ⇒ nil
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
3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 |
# File 'ext/pg_connection.c', line 3887
static VALUE
pgconn_send_flush_request(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = PQsendFlushRequest(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
|
#send_pipeline_sync ⇒ nil
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
3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 |
# File 'ext/pg_connection.c', line 3862
static VALUE
pgconn_send_pipeline_sync(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = gvl_PQsendPipelineSync(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
|
#send_prepare(stmt_name, sql[, param_types ]) ⇒ nil
Prepares statement sql with name name to be executed later. Sends prepare command asynchronously, and returns immediately. On failure, it raises a 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.
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 |
# File 'ext/pg_connection.c', line 2057
static VALUE
pgconn_send_prepare(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
int result;
VALUE name, command, in_paramtypes;
VALUE param;
int i = 0;
int nParams = 0;
Oid *paramTypes = NULL;
const char *name_cstr;
const char *command_cstr;
int enc_idx = this->enc_idx;
rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
name_cstr = pg_cstr_enc(name, enc_idx);
command_cstr = pg_cstr_enc(command, enc_idx);
if(! NIL_P(in_paramtypes)) {
Check_Type(in_paramtypes, T_ARRAY);
nParams = (int)RARRAY_LEN(in_paramtypes);
paramTypes = ALLOC_N(Oid, nParams);
for(i = 0; i < nParams; i++) {
param = rb_ary_entry(in_paramtypes, i);
if(param == Qnil)
paramTypes[i] = 0;
else
paramTypes[i] = NUM2UINT(param);
}
}
result = gvl_PQsendPrepare(this->pgconn, name_cstr, command_cstr, nParams, paramTypes);
xfree(paramTypes);
if(result == 0) {
pg_raise_conn_error( rb_eUnableToSend, self, "PQsendPrepare %s", PQerrorMessage(this->pgconn));
}
pgconn_wait_for_flush( self );
return Qnil;
}
|
#send_query(sql) ⇒ nil
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.
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 |
# File 'ext/pg_connection.c', line 1948
static VALUE
pgconn_send_query(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
/* If called with no or nil parameters, use PQexec for compatibility */
if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
if(gvl_PQsendQuery(this->pgconn, pg_cstr_enc(argv[0], this->enc_idx)) == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "PQsendQuery %s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
pg_deprecated(2, ("forwarding async_exec to async_exec_params and send_query to send_query_params is deprecated"));
/* If called with parameters, and optionally result_format,
* use PQsendQueryParams
*/
return pgconn_send_query_params( argc, argv, self);
}
|
#send_query_params(sql, params[, result_format [, type_map ]]) ⇒ nil
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.
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 |
# File 'ext/pg_connection.c', line 2008
static VALUE
pgconn_send_query_params(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
int result;
VALUE command, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
rb_scan_args(argc, argv, "22", &command, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 1;
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQsendQueryParams(this->pgconn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);
free_query_params( ¶msData );
if(result == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "PQsendQueryParams %s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
|
#send_query_prepared(statement_name[, params, result_format[, type_map ]]) ⇒ Object #- ⇒ Object
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.
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 |
# File 'ext/pg_connection.c', line 2130
static VALUE
pgconn_send_query_prepared(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
int result;
VALUE name, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
rb_scan_args(argc, argv, "13", &name, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 0;
if(NIL_P(paramsData.params)) {
paramsData.params = rb_ary_new2(0);
}
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQsendQueryPrepared(this->pgconn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
resultFormat);
free_query_params( ¶msData );
if(result == 0)
pg_raise_conn_error( rb_eUnableToSend, self, "PQsendQueryPrepared %s", PQerrorMessage(this->pgconn));
pgconn_wait_for_flush( self );
return Qnil;
}
|
#server_version ⇒ Integer
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).
886 887 888 889 890 891 892 893 894 |
# File 'ext/pg_connection.c', line 886
static VALUE
pgconn_server_version(VALUE self)
{
int server_version = PQserverVersion(pg_get_pgconn(self));
if (server_version == 0) {
pg_raise_conn_error( rb_eConnectionBad, self, "PQserverVersion() can't get server version");
}
return INT2NUM(server_version);
}
|
#set_chunked_rows_mode ⇒ self
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
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 |
# File 'ext/pg_connection.c', line 1920
static VALUE
pgconn_set_chunked_rows_mode(VALUE self, VALUE chunk_size)
{
PGconn *conn = pg_get_pgconn(self);
rb_check_frozen(self);
if( PQsetChunkedRowsMode(conn, NUM2INT(chunk_size)) == 0 )
pg_raise_conn_error( rb_ePGerror, self, "PQsetChunkedRowsMode %s", PQerrorMessage(conn));
return self;
}
|
#set_client_encoding(encoding) ⇒ Object Also known as: async_set_client_encoding, client_encoding=
Sets the client encoding to the encoding String.
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 |
# File 'ext/pg_connection.c', line 4344
static VALUE
pgconn_async_set_client_encoding(VALUE self, VALUE encname)
{
VALUE query_format, query;
rb_check_frozen(self);
Check_Type(encname, T_STRING);
query_format = rb_str_new_cstr("set client_encoding to '%s'");
query = rb_funcall(query_format, rb_intern("%"), 1, encname);
pgconn_async_exec(1, &query, self);
pgconn_set_internal_encoding_index( self );
return Qnil;
}
|
#set_default_encoding ⇒ Encoding
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.
4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 |
# File 'ext/pg_connection.c', line 4395
static VALUE
pgconn_set_default_encoding( VALUE self )
{
PGconn *conn = pg_get_pgconn( self );
rb_encoding *rb_enc;
rb_check_frozen(self);
if (( rb_enc = rb_default_internal_encoding() )) {
rb_encoding * conn_encoding = pg_conn_enc_get( conn );
/* Don't set the server encoding, if it's unnecessary.
* This is important for connection proxies, who disallow configuration settings.
*/
if ( conn_encoding != rb_enc ) {
const char *encname = pg_get_rb_encoding_as_pg_encoding( rb_enc );
if ( pgconn_set_client_encoding_async(self, rb_str_new_cstr(encname)) != 0 )
rb_warning( "Failed to set the default_internal encoding to %s: '%s'",
encname, PQerrorMessage(conn) );
}
pgconn_set_internal_encoding_index( self );
return rb_enc_from_encoding( rb_enc );
} else {
pgconn_set_internal_encoding_index( self );
return Qnil;
}
}
|
#set_error_context_visibility(context_visibility) ⇒ Integer
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.
2855 2856 2857 2858 2859 2860 2861 |
# File 'ext/pg_connection.c', line 2855
static VALUE
pgconn_set_error_context_visibility(VALUE self, VALUE in_context_visibility)
{
PGconn *conn = pg_get_pgconn(self);
PGContextVisibility context_visibility = NUM2INT(in_context_visibility);
return INT2FIX(PQsetErrorContextVisibility(conn, context_visibility));
}
|
#set_error_verbosity(verbosity) ⇒ Integer
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.
2827 2828 2829 2830 2831 2832 2833 |
# File 'ext/pg_connection.c', line 2827
static VALUE
pgconn_set_error_verbosity(VALUE self, VALUE in_verbosity)
{
PGconn *conn = pg_get_pgconn(self);
PGVerbosity verbosity = NUM2INT(in_verbosity);
return INT2FIX(PQsetErrorVerbosity(conn, verbosity));
}
|
#set_notice_processor {|message| ... } ⇒ Proc
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.
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 |
# File 'ext/pg_connection.c', line 3036
static VALUE
pgconn_set_notice_processor(VALUE self)
{
VALUE proc, old_proc;
t_pg_connection *this = pg_get_connection_safe( self );
rb_check_frozen(self);
/* If default_notice_processor is unset, assume that the current
* notice processor is the default, and save it to a global variable.
* This should not be a problem because the default processor is
* always the same, so won't vary among connections.
*/
if(this->default_notice_processor == NULL)
this->default_notice_processor = PQsetNoticeProcessor(this->pgconn, NULL, NULL);
old_proc = this->notice_processor;
if( rb_block_given_p() ) {
proc = rb_block_proc();
PQsetNoticeProcessor(this->pgconn, gvl_notice_processor_proxy, (void *)self);
} else {
/* if no block is given, set back to default */
proc = Qnil;
PQsetNoticeProcessor(this->pgconn, this->default_notice_processor, NULL);
}
RB_OBJ_WRITE(self, &this->notice_processor, proc);
return old_proc;
}
|
#set_notice_receiver {|result| ... } ⇒ Proc
Notice and warning messages generated by the server are not returned by the query execution functions, since they do not imply failure of the query. Instead they are passed to a notice handling function, and execution continues normally after the handler returns. The default notice handling function prints the message on stderr
, but the application can override this behavior by supplying its own handling function.
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.
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 |
# File 'ext/pg_connection.c', line 2975
static VALUE
pgconn_set_notice_receiver(VALUE self)
{
VALUE proc, old_proc;
t_pg_connection *this = pg_get_connection_safe( self );
rb_check_frozen(self);
/* If default_notice_receiver is unset, assume that the current
* notice receiver is the default, and save it to a global variable.
* This should not be a problem because the default receiver is
* always the same, so won't vary among connections.
*/
if(this->default_notice_receiver == NULL)
this->default_notice_receiver = PQsetNoticeReceiver(this->pgconn, NULL, NULL);
old_proc = this->notice_receiver;
if( rb_block_given_p() ) {
proc = rb_block_proc();
PQsetNoticeReceiver(this->pgconn, gvl_notice_receiver_proxy, (void *)self);
} else {
/* if no block is given, set back to default */
proc = Qnil;
PQsetNoticeReceiver(this->pgconn, this->default_notice_receiver, NULL);
}
RB_OBJ_WRITE(self, &this->notice_receiver, proc);
return old_proc;
}
|
#set_single_row_mode ⇒ self
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
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 |
# File 'ext/pg_connection.c', line 1882
static VALUE
pgconn_set_single_row_mode(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
rb_check_frozen(self);
if( PQsetSingleRowMode(conn) == 0 )
pg_raise_conn_error( rb_ePGerror, self, "PQsetSingleRowMode %s", PQerrorMessage(conn));
return self;
}
|
#setnonblocking(enabled) ⇒ Object Also known as: async_setnonblocking
call-seq:
conn.setnonblocking(Boolean) -> nil
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
.
462 463 464 465 466 |
# File 'lib/pg/connection.rb', line 462 def setnonblocking(enabled) singleton_class.async_send_api = !enabled self.flush_data = !enabled sync_setnonblocking(true) end |
#socket ⇒ Integer
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.
930 931 932 933 934 935 936 937 938 939 940 |
# File 'ext/pg_connection.c', line 930
static VALUE
pgconn_socket(VALUE self)
{
int sd;
pg_deprecated(4, ("conn.socket is deprecated and should be replaced by conn.socket_io"));
if( (sd = PQsocket(pg_get_pgconn(self))) < 0)
pg_raise_conn_error( rb_eConnectionBad, self, "PQsocket() can't get socket descriptor");
return INT2NUM(sd);
}
|
#socket_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.
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 |
# File 'ext/pg_connection.c', line 985
static VALUE
pgconn_socket_io(VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
if ( !RTEST(this->socket_io) ) {
int sd;
if( (sd = PQsocket(this->pgconn)) < 0){
pg_raise_conn_error( rb_eConnectionBad, self, "PQsocket() can't get socket descriptor");
}
return pg_wrap_socket_io( sd, self, &this->socket_io, &this->ruby_sd);
}
return this->socket_io;
}
|
#ssl_attribute(attribute_name) ⇒ String
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.
3723 3724 3725 3726 3727 3728 3729 3730 |
# File 'ext/pg_connection.c', line 3723
static VALUE
pgconn_ssl_attribute(VALUE self, VALUE attribute_name)
{
const char *p_attr;
p_attr = PQsslAttribute(pg_get_pgconn(self), StringValueCStr(attribute_name));
return p_attr ? rb_str_new_cstr(p_attr) : Qnil;
}
|
#ssl_attribute_names ⇒ Array<String>
Return an array of SSL attribute names available.
See also #ssl_attribute
3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 |
# File 'ext/pg_connection.c', line 3741
static VALUE
pgconn_ssl_attribute_names(VALUE self)
{
int i;
const char * const * p_list = PQsslAttributeNames(pg_get_pgconn(self));
VALUE ary = rb_ary_new();
for ( i = 0; p_list[i]; i++ ) {
rb_ary_push( ary, rb_str_new_cstr( p_list[i] ));
}
return ary;
}
|
#ssl_attributes ⇒ Object
call-seq:
conn.ssl_attributes -> Hash<String,String>
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
368 369 370 371 372 |
# File 'lib/pg/connection.rb', line 368 def ssl_attributes ssl_attribute_names.each.with_object({}) do |n,h| h[n] = ssl_attribute(n) end end |
#ssl_in_use? ⇒ Boolean
Returns true
if the connection uses SSL/TLS, false
if not.
3690 3691 3692 3693 3694 |
# File 'ext/pg_connection.c', line 3690
static VALUE
pgconn_ssl_in_use(VALUE self)
{
return PQsslInUse(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
|
#status ⇒ Object
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
793 794 795 796 797 |
# File 'ext/pg_connection.c', line 793
static VALUE
pgconn_status(VALUE self)
{
return INT2NUM(PQstatus(pg_get_pgconn(self)));
}
|
#sync_cancel ⇒ Object
PostgreSQL-17+
608 609 610 611 612 613 |
# File 'lib/pg/connection.rb', line 608 def sync_cancel cancon = PG::CancelConnection.new(self) cancon.sync_cancel rescue PG::Error => err err.to_s end |
#sync_close_portal(portal_name) ⇒ PG::Result
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.
1617 1618 1619 1620 1621 |
# File 'ext/pg_connection.c', line 1617
static VALUE
pgconn_sync_close_portal(VALUE self, VALUE stmt_name)
{
return pgconn_sync_describe_close_prepared_portal(self, stmt_name, gvl_PQclosePortal);
}
|
#sync_close_prepared(stmt_name) ⇒ PG::Result
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.
1601 1602 1603 1604 1605 |
# File 'ext/pg_connection.c', line 1601
static VALUE
pgconn_sync_close_prepared(VALUE self, VALUE stmt_name)
{
return pgconn_sync_describe_close_prepared_portal(self, stmt_name, gvl_PQclosePrepared);
}
|
#sync_describe_portal(portal_name) ⇒ PG::Result
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.
1583 1584 1585 1586 1587 |
# File 'ext/pg_connection.c', line 1583
static VALUE
pgconn_sync_describe_portal(VALUE self, VALUE stmt_name)
{
return pgconn_sync_describe_close_prepared_portal(self, stmt_name, gvl_PQdescribePortal);
}
|
#sync_describe_prepared(statement_name) ⇒ PG::Result
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.
1568 1569 1570 1571 1572 |
# File 'ext/pg_connection.c', line 1568
static VALUE
pgconn_sync_describe_prepared(VALUE self, VALUE stmt_name)
{
return pgconn_sync_describe_close_prepared_portal(self, stmt_name, gvl_PQdescribePrepared);
}
|
#sync_encrypt_password(*args) ⇒ Object
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 |
# File 'ext/pg_connection.c', line 423
static VALUE
pgconn_sync_encrypt_password(int argc, VALUE *argv, VALUE self)
{
char *encrypted = NULL;
VALUE rval = Qnil;
VALUE password, username, algorithm;
PGconn *conn = pg_get_pgconn(self);
rb_scan_args( argc, argv, "21", &password, &username, &algorithm );
Check_Type(password, T_STRING);
Check_Type(username, T_STRING);
encrypted = gvl_PQencryptPasswordConn(conn, StringValueCStr(password), StringValueCStr(username), RTEST(algorithm) ? StringValueCStr(algorithm) : NULL);
if ( encrypted ) {
rval = rb_str_new2( encrypted );
PQfreemem( encrypted );
} else {
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
}
return rval;
}
|
#sync_exec(sql) ⇒ PG::Result #sync_exec(sql) {|pg_result| ... } ⇒ Object
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_exec can be aborted by signals (like Ctrl-C), while #exec blocks 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.
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 |
# File 'ext/pg_connection.c', line 1109
static VALUE
pgconn_sync_exec(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
/* If called with no or nil parameters, use PQexec for compatibility */
if ( argc == 1 || (argc >= 2 && argc <= 4 && NIL_P(argv[1]) )) {
VALUE query_str = argv[0];
result = gvl_PQexec(this->pgconn, pg_cstr_enc(query_str, this->enc_idx));
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
pg_deprecated(0, ("forwarding exec to exec_params is deprecated"));
/* Otherwise, just call #exec_params instead for backward-compatibility */
return pgconn_sync_exec_params( argc, argv, self );
}
|
#sync_exec_params(sql, params[, result_format[, type_map]]) ⇒ PG::Result #sync_exec_params(sql, params[, result_format[, type_map]]) {|pg_result| ... } ⇒ Object
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.
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 |
# File 'ext/pg_connection.c', line 1410
static VALUE
pgconn_sync_exec_params( int argc, VALUE *argv, VALUE self )
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
VALUE command, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
/* For compatibility we accept 1 to 4 parameters */
rb_scan_args(argc, argv, "13", &command, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 1;
/*
* For backward compatibility no or +nil+ for the second parameter
* is passed to #exec
*/
if ( NIL_P(paramsData.params) ) {
pg_deprecated(1, ("forwarding exec_params to exec is deprecated"));
return pgconn_sync_exec( 1, argv, self );
}
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQexecParams(this->pgconn, pg_cstr_enc(command, paramsData.enc_idx), nParams, paramsData.types,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats, resultFormat);
free_query_params( ¶msData );
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
|
#sync_exec_prepared(statement_name[, params, result_format[, type_map]]) ⇒ PG::Result #sync_exec_prepared(statement_name[, params, result_format[, type_map]]) {|pg_result| ... } ⇒ Object
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.
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 |
# File 'ext/pg_connection.c', line 1510
static VALUE
pgconn_sync_exec_prepared(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
VALUE name, in_res_fmt;
int nParams;
int resultFormat;
struct query_params_data paramsData = { this->enc_idx };
rb_scan_args(argc, argv, "13", &name, ¶msData.params, &in_res_fmt, ¶msData.typemap);
paramsData.with_types = 0;
if(NIL_P(paramsData.params)) {
paramsData.params = rb_ary_new2(0);
}
pgconn_query_assign_typemap( self, ¶msData );
resultFormat = NIL_P(in_res_fmt) ? 0 : NUM2INT(in_res_fmt);
nParams = alloc_query_params( ¶msData );
result = gvl_PQexecPrepared(this->pgconn, pg_cstr_enc(name, paramsData.enc_idx), nParams,
(const char * const *)paramsData.values, paramsData.lengths, paramsData.formats,
resultFormat);
free_query_params( ¶msData );
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult,
pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
|
#sync_flush ⇒ Object
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 |
# File 'ext/pg_connection.c', line 2324
static VALUE
pgconn_sync_flush(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int ret = PQflush(conn);
if(ret == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return (ret) ? Qfalse : Qtrue;
}
|
#sync_get_copy_data(*args) ⇒ Object
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 |
# File 'ext/pg_connection.c', line 2766
static VALUE
pgconn_sync_get_copy_data(int argc, VALUE *argv, VALUE self )
{
VALUE async_in;
VALUE result;
int ret;
char *buffer;
VALUE decoder;
t_pg_coder *p_coder = NULL;
t_pg_connection *this = pg_get_connection_safe( self );
rb_scan_args(argc, argv, "02", &async_in, &decoder);
if( NIL_P(decoder) ){
if( !NIL_P(this->decoder_for_get_copy_data) ){
p_coder = RTYPEDDATA_DATA( this->decoder_for_get_copy_data );
}
} else {
/* Check argument type and use argument decoder */
TypedData_Get_Struct(decoder, t_pg_coder, &pg_coder_type, p_coder);
}
ret = gvl_PQgetCopyData(this->pgconn, &buffer, RTEST(async_in));
if(ret == -2){ /* error */
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
}
if(ret == -1) { /* No data left */
return Qnil;
}
if(ret == 0) { /* would block */
return Qfalse;
}
if( p_coder ){
t_pg_coder_dec_func dec_func = pg_coder_dec_func( p_coder, p_coder->format );
result = dec_func( p_coder, buffer, ret, 0, 0, this->enc_idx );
} else {
result = rb_str_new(buffer, ret);
}
PQfreemem(buffer);
return result;
}
|
#sync_get_last_result ⇒ PG::Result
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.
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 |
# File 'ext/pg_connection.c', line 3210
static VALUE
pgconn_sync_get_last_result(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
VALUE rb_pgresult = Qnil;
PGresult *cur, *prev;
cur = prev = NULL;
while ((cur = gvl_PQgetResult(conn)) != NULL) {
int status;
if (prev) PQclear(prev);
prev = cur;
status = PQresultStatus(cur);
if (status == PGRES_COPY_OUT || status == PGRES_COPY_IN || status == PGRES_COPY_BOTH)
break;
}
if (prev) {
rb_pgresult = pg_new_result( prev, self );
pg_result_check(rb_pgresult);
}
return rb_pgresult;
}
|
#sync_get_result ⇒ Object
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 |
# File 'ext/pg_connection.c', line 2246
static VALUE
pgconn_sync_get_result(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
PGresult *result;
VALUE rb_pgresult;
result = gvl_PQgetResult(conn);
if(result == NULL)
return Qnil;
rb_pgresult = pg_new_result(result, self);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, rb_pgresult,
pg_result_clear, rb_pgresult);
}
return rb_pgresult;
}
|
#sync_isnonblocking ⇒ Object
2318 2319 2320 2321 2322 |
# File 'ext/pg_connection.c', line 2318
static VALUE
pgconn_sync_isnonblocking(VALUE self)
{
return PQisnonblocking(pg_get_pgconn(self)) ? Qtrue : Qfalse;
}
|
#sync_pipeline_sync ⇒ nil
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
3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 |
# File 'ext/pg_connection.c', line 3837
static VALUE
pgconn_sync_pipeline_sync(VALUE self)
{
PGconn *conn = pg_get_pgconn(self);
int res = gvl_PQpipelineSync(conn);
if( res != 1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
|
#sync_prepare(stmt_name, sql[, param_types ]) ⇒ PG::Result
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.
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 |
# File 'ext/pg_connection.c', line 1461
static VALUE
pgconn_sync_prepare(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGresult *result = NULL;
VALUE rb_pgresult;
VALUE name, command, in_paramtypes;
VALUE param;
int i = 0;
int nParams = 0;
Oid *paramTypes = NULL;
const char *name_cstr;
const char *command_cstr;
int enc_idx = this->enc_idx;
rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes);
name_cstr = pg_cstr_enc(name, enc_idx);
command_cstr = pg_cstr_enc(command, enc_idx);
if(! NIL_P(in_paramtypes)) {
Check_Type(in_paramtypes, T_ARRAY);
nParams = (int)RARRAY_LEN(in_paramtypes);
paramTypes = ALLOC_N(Oid, nParams);
for(i = 0; i < nParams; i++) {
param = rb_ary_entry(in_paramtypes, i);
if(param == Qnil)
paramTypes[i] = 0;
else
paramTypes[i] = NUM2UINT(param);
}
}
result = gvl_PQprepare(this->pgconn, name_cstr, command_cstr, nParams, paramTypes);
xfree(paramTypes);
rb_pgresult = pg_new_result(result, self);
pg_result_check(rb_pgresult);
return rb_pgresult;
}
|
#sync_put_copy_data(*args) ⇒ Object
**** PG::Connection INSTANCE METHODS: COPY *****
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 |
# File 'ext/pg_connection.c', line 2693
static VALUE
pgconn_sync_put_copy_data(int argc, VALUE *argv, VALUE self)
{
int ret;
int len;
t_pg_connection *this = pg_get_connection_safe( self );
VALUE value;
VALUE buffer = Qnil;
VALUE encoder;
VALUE intermediate = Qnil;
t_pg_coder *p_coder = NULL;
rb_scan_args( argc, argv, "11", &value, &encoder );
if( NIL_P(encoder) ){
if( NIL_P(this->encoder_for_put_copy_data) ){
buffer = value;
} else {
p_coder = RTYPEDDATA_DATA( this->encoder_for_put_copy_data );
}
} else {
/* Check argument type and use argument encoder */
TypedData_Get_Struct(encoder, t_pg_coder, &pg_coder_type, p_coder);
}
if( p_coder ){
t_pg_coder_enc_func enc_func;
int enc_idx = this->enc_idx;
enc_func = pg_coder_enc_func( p_coder );
len = enc_func( p_coder, value, NULL, &intermediate, enc_idx);
if( len == -1 ){
/* The intermediate value is a String that can be used directly. */
buffer = intermediate;
} else {
buffer = rb_str_new(NULL, len);
len = enc_func( p_coder, value, RSTRING_PTR(buffer), &intermediate, enc_idx);
rb_str_set_len( buffer, len );
}
}
Check_Type(buffer, T_STRING);
ret = gvl_PQputCopyData(this->pgconn, RSTRING_PTR(buffer), RSTRING_LENINT(buffer));
if(ret == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
RB_GC_GUARD(buffer);
return (ret) ? Qtrue : Qfalse;
}
|
#sync_put_copy_end(*args) ⇒ Object
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 |
# File 'ext/pg_connection.c', line 2746
static VALUE
pgconn_sync_put_copy_end(int argc, VALUE *argv, VALUE self)
{
VALUE str;
int ret;
const char *error_message = NULL;
t_pg_connection *this = pg_get_connection_safe( self );
if (rb_scan_args(argc, argv, "01", &str) == 0)
error_message = NULL;
else
error_message = pg_cstr_enc(str, this->enc_idx);
ret = gvl_PQputCopyEnd(this->pgconn, error_message);
if(ret == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(this->pgconn));
return (ret) ? Qtrue : Qfalse;
}
|
#sync_reset ⇒ Object
558 559 560 561 562 563 564 |
# File 'ext/pg_connection.c', line 558
static VALUE
pgconn_sync_reset( VALUE self )
{
pgconn_close_socket_io( self );
gvl_PQreset( pg_get_pgconn(self) );
return self;
}
|
#sync_set_client_encoding(encoding) ⇒ Object
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.
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 |
# File 'ext/pg_connection.c', line 3088
static VALUE
pgconn_sync_set_client_encoding(VALUE self, VALUE str)
{
PGconn *conn = pg_get_pgconn( self );
rb_check_frozen(self);
Check_Type(str, T_STRING);
if ( (gvl_PQsetClientEncoding(conn, StringValueCStr(str))) == -1 )
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
pgconn_set_internal_encoding_index( self );
return Qnil;
}
|
#sync_setnonblocking(state) ⇒ Object
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 |
# File 'ext/pg_connection.c', line 2298
static VALUE
pgconn_sync_setnonblocking(VALUE self, VALUE state)
{
int arg;
PGconn *conn = pg_get_pgconn(self);
rb_check_frozen(self);
if(state == Qtrue)
arg = 1;
else if (state == Qfalse)
arg = 0;
else
rb_raise(rb_eArgError, "Boolean value expected");
if(PQsetnonblocking(conn, arg) == -1)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(conn));
return Qnil;
}
|
#trace(stream) ⇒ nil
Enables tracing message passing between backend. The trace message will be written to the stream stream, which must implement a method fileno
that returns a writable file descriptor.
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 |
# File 'ext/pg_connection.c', line 2872
static VALUE
pgconn_trace(VALUE self, VALUE stream)
{
VALUE fileno;
FILE *new_fp;
int old_fd, new_fd;
VALUE new_file;
t_pg_connection *this = pg_get_connection_safe( self );
rb_check_frozen(self);
if(!rb_respond_to(stream,rb_intern("fileno")))
rb_raise(rb_eArgError, "stream does not respond to method: fileno");
fileno = rb_funcall(stream, rb_intern("fileno"), 0);
if(fileno == Qnil)
rb_raise(rb_eArgError, "can't get file descriptor from stream");
/* Duplicate the file descriptor and re-open
* it. Then, make it into a ruby File object
* and assign it to an instance variable.
* This prevents a problem when the File
* object passed to this function is closed
* before the connection object is. */
old_fd = NUM2INT(fileno);
new_fd = dup(old_fd);
new_fp = fdopen(new_fd, "w");
if(new_fp == NULL)
rb_raise(rb_eArgError, "stream is not writable");
new_file = rb_funcall(rb_cIO, rb_intern("new"), 1, INT2NUM(new_fd));
RB_OBJ_WRITE(self, &this->trace_stream, new_file);
PQtrace(this->pgconn, new_fp);
return Qnil;
}
|
#transaction ⇒ Object
call-seq:
conn.transaction { |conn| ... } -> result of the block
Executes a BEGIN
at the start of the block, and a COMMIT
at the end of the block, or ROLLBACK
if any exception occurs.
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 |
# File 'lib/pg/connection.rb', line 308 def transaction rollback = false exec "BEGIN" yield(self) rescue PG::RollbackTransaction rollback = true cancel if transaction_status == PG::PQTRANS_ACTIVE block exec "ROLLBACK" rescue Exception rollback = true cancel if transaction_status == PG::PQTRANS_ACTIVE block exec "ROLLBACK" raise ensure exec "COMMIT" unless rollback end |
#transaction_status ⇒ Object
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)
810 811 812 813 814 |
# File 'ext/pg_connection.c', line 810
static VALUE
pgconn_transaction_status(VALUE self)
{
return INT2NUM(PQtransactionStatus(pg_get_pgconn(self)));
}
|
#tty ⇒ Object
Obsolete function.
735 736 737 738 739 |
# File 'ext/pg_connection.c', line 735
static VALUE
pgconn_tty(VALUE self)
{
return rb_str_new2("");
}
|
#type_map_for_queries ⇒ TypeMap
Returns the default TypeMap that is currently set for type casts of query bind parameters.
4456 4457 4458 4459 4460 4461 4462 |
# File 'ext/pg_connection.c', line 4456
static VALUE
pgconn_type_map_for_queries_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->type_map_for_queries;
}
|
#type_map_for_queries=(typemap) ⇒ Object
Set the default TypeMap that is used for type casts of query bind parameters.
typemap
must be a kind of PG::TypeMap .
4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 |
# File 'ext/pg_connection.c', line 4432
static VALUE
pgconn_type_map_for_queries_set(VALUE self, VALUE typemap)
{
t_pg_connection *this = pg_get_connection( self );
t_typemap *tm;
UNUSED(tm);
rb_check_frozen(self);
/* Check type of method param */
TypedData_Get_Struct(typemap, t_typemap, &pg_typemap_type, tm);
RB_OBJ_WRITE(self, &this->type_map_for_queries, typemap);
return typemap;
}
|
#type_map_for_results ⇒ TypeMap
Returns the default TypeMap that is currently set for type casts of result values.
4494 4495 4496 4497 4498 4499 4500 |
# File 'ext/pg_connection.c', line 4494
static VALUE
pgconn_type_map_for_results_get(VALUE self)
{
t_pg_connection *this = pg_get_connection( self );
return this->type_map_for_results;
}
|
#type_map_for_results=(typemap) ⇒ Object
Set the default TypeMap that is used for type casts of result values.
typemap
must be a kind of PG::TypeMap .
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 |
# File 'ext/pg_connection.c', line 4473
static VALUE
pgconn_type_map_for_results_set(VALUE self, VALUE typemap)
{
t_pg_connection *this = pg_get_connection( self );
t_typemap *tm;
UNUSED(tm);
rb_check_frozen(self);
TypedData_Get_Struct(typemap, t_typemap, &pg_typemap_type, tm);
RB_OBJ_WRITE(self, &this->type_map_for_results, typemap);
return typemap;
}
|
#PG::Connection.unescape_bytea(string) ⇒ Object
Converts an escaped string representation of binary data into binary data — the reverse of #escape_bytea. This is needed when retrieving bytea
data in text format, but not when retrieving it in binary format.
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 |
# File 'ext/pg_connection.c', line 1764
static VALUE
pgconn_s_unescape_bytea(VALUE self, VALUE str)
{
unsigned char *from, *to;
size_t to_len;
VALUE ret;
UNUSED( self );
Check_Type(str, T_STRING);
from = (unsigned char*)StringValueCStr(str);
to = PQunescapeBytea(from, &to_len);
ret = rb_str_new((char*)to, to_len);
PQfreemem(to);
return ret;
}
|
#untrace ⇒ nil
Disables the message tracing.
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 |
# File 'ext/pg_connection.c', line 2915
static VALUE
pgconn_untrace(VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PQuntrace(this->pgconn);
rb_funcall(this->trace_stream, rb_intern("close"), 0);
RB_OBJ_WRITE(self, &this->trace_stream, Qnil);
return Qnil;
}
|
#user ⇒ Object
Returns the authenticated user name.
646 647 648 649 650 651 652 |
# File 'ext/pg_connection.c', line 646
static VALUE
pgconn_user(VALUE self)
{
char *user = PQuser(pg_get_pgconn(self));
if (!user) return Qnil;
return rb_str_new2(user);
}
|
#wait_for_notify([ timeout ]) {|event, pid, payload| ... } ⇒ String Also known as: notifies_wait
Blocks while waiting for notification(s), or until the optional timeout is reached, whichever comes first. timeout is measured in seconds and can be fractional.
Returns nil
if timeout is reached, the name of the NOTIFY event otherwise. If used in block form, passes the name of the NOTIFY event
, the generating pid
and the optional payload
string into the block.
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 |
# File 'ext/pg_connection.c', line 2653
static VALUE
pgconn_wait_for_notify(int argc, VALUE *argv, VALUE self)
{
t_pg_connection *this = pg_get_connection_safe( self );
PGnotify *pnotification;
struct timeval timeout;
struct timeval *ptimeout = NULL;
VALUE timeout_in = Qnil, relname = Qnil, be_pid = Qnil, extra = Qnil;
double timeout_sec;
rb_scan_args( argc, argv, "01", &timeout_in );
if ( RTEST(timeout_in) ) {
timeout_sec = NUM2DBL( timeout_in );
timeout.tv_sec = (time_t)timeout_sec;
timeout.tv_usec = (suseconds_t)( (timeout_sec - (long)timeout_sec) * 1e6 );
ptimeout = &timeout;
}
pnotification = (PGnotify*) wait_socket_readable( self, ptimeout, notify_readable);
/* Return nil if the select timed out */
if ( !pnotification ) return Qnil;
relname = rb_str_new2( pnotification->relname );
PG_ENCODING_SET_NOCHECK( relname, this->enc_idx );
be_pid = INT2NUM( pnotification->be_pid );
if ( *pnotification->extra ) {
extra = rb_str_new2( pnotification->extra );
PG_ENCODING_SET_NOCHECK( extra, this->enc_idx );
}
PQfreemem( pnotification );
if ( rb_block_given_p() )
rb_yield_values( 3, relname, be_pid, extra );
return relname;
}
|