class Sequel::Postgres::Database

  1. lib/sequel/adapters/postgres.rb
Superclass: Sequel::Database

Constants

DATABASE_ERROR_CLASSES = [PGError].freeze  

simplecov:enable

Public Instance methods

bound_variable_arg(arg, conn)

Convert given argument so that it can be used directly by pg. Currently, pg doesn’t handle fractional seconds in Time/DateTime or blobs with “0”. Only public for use by the adapter, shouldn’t be used by external code.

[show source]
    # File lib/sequel/adapters/postgres.rb
184 def bound_variable_arg(arg, conn)
185   case arg
186   when Sequel::SQL::Blob
187     {:value=>arg, :type=>17, :format=>1}
188   # simplecov:disable
189   # Not covered by tests as tests use pg_extended_date_support
190   # extension, which has basically the same code.
191   when Time, DateTime
192     @default_dataset.literal_date_or_time(arg)
193   # simplecov:enable
194   else
195     arg
196   end
197 end
call_procedure(name, *args)

Call a procedure with the given name and arguments. Returns a hash if the procedure returns a value, and nil otherwise. Example:

DB.call_procedure(:foo, 1, 2)
# CALL foo(1, 2)
[show source]
    # File lib/sequel/adapters/postgres.rb
204 def call_procedure(name, *args)
205   dataset.send(:call_procedure, name, args)
206 end
connect(server)

Connects to the database. In addition to the standard database options, using the :encoding or :charset option changes the client encoding for the connection, :connect_timeout is a connection timeout in seconds, :sslmode sets whether postgres’s sslmode, and :notice_receiver handles server notices in a proc. :connect_timeout, :driver_options, :sslmode, and :notice_receiver are only supported if the pg driver is used.

[show source]
    # File lib/sequel/adapters/postgres.rb
215 def connect(server)
216   opts = server_opts(server)
217   if USES_PG
218     connection_params = {
219       :host => opts[:host],
220       :port => opts[:port],
221       :dbname => opts[:database],
222       :user => opts[:user],
223       :password => opts[:password],
224       :connect_timeout => opts[:connect_timeout] || 20,
225       :sslmode => opts[:sslmode],
226       :sslrootcert => opts[:sslrootcert]
227     }.delete_if { |key, value| blank_object?(value) }
228     # simplecov:disable
229     connection_params.merge!(opts[:driver_options]) if opts[:driver_options]
230     # simplecov:enable
231     conn = Adapter.connect(opts[:conn_str] || connection_params)
232 
233     conn.instance_variable_set(:@prepared_statements, {})
234 
235     if receiver = opts[:notice_receiver]
236       conn.set_notice_receiver(&receiver)
237     end
238 
239     # simplecov:disable
240     if conn.respond_to?(:type_map_for_queries=) && defined?(PG_QUERY_TYPE_MAP)
241     # simplecov:enable
242       conn.type_map_for_queries = PG_QUERY_TYPE_MAP
243     end
244   # simplecov:disable
245   else
246     unless typecast_value_boolean(@opts.fetch(:force_standard_strings, true))
247       raise Error, "Cannot create connection using postgres-pr unless force_standard_strings is set"
248     end
249 
250     conn = Adapter.connect(
251       (opts[:host] unless blank_object?(opts[:host])),
252       opts[:port] || 5432,
253       nil, '',
254       opts[:database],
255       opts[:user],
256       opts[:password]
257     )
258   end
259   # simplecov:enable
260 
261   conn.instance_variable_set(:@db, self)
262 
263   # simplecov:disable
264   if encoding = opts[:encoding] || opts[:charset]
265     if conn.respond_to?(:set_client_encoding)
266       conn.set_client_encoding(encoding)
267     else
268       conn.async_exec("set client_encoding to '#{encoding}'")
269     end
270   end
271   # simplecov:enable
272 
273   connection_configuration_sqls(opts).each{|sql| conn.execute(sql)}
274   conn
275 end
convert_infinite_timestamps()

Always false, support was moved to pg_extended_date_support extension. Needs to stay defined here so that sequel_pg works.

[show source]
    # File lib/sequel/adapters/postgres.rb
279 def convert_infinite_timestamps
280   false
281 end
convert_infinite_timestamps=(v)

Enable pg_extended_date_support extension if symbol or string is given.

[show source]
    # File lib/sequel/adapters/postgres.rb
284 def convert_infinite_timestamps=(v)
285   case v
286   when Symbol, String, true
287     extension(:pg_extended_date_support)
288     self.convert_infinite_timestamps = v
289   end
290 end
copy_into(table, opts=OPTS)

copy_into uses PostgreSQL’s +COPY FROM STDIN+ SQL statement to do very fast inserts into a table using input preformatting in either CSV or PostgreSQL text format. This method is only supported if pg 0.14.0+ is the underlying ruby driver. This method should only be called if you want results returned to the client. If you are using +COPY FROM+ with a filename, you should just use run instead of this method.

The following options are respected:

:columns

The columns to insert into, with the same order as the columns in the input data. If this isn’t given, uses all columns in the table.

:data

The data to copy to PostgreSQL, which should already be in CSV or PostgreSQL text format. This can be either a string, or any object that responds to each and yields string.

:format

The format to use. text is the default, so this should be :csv or :binary.

:options

An options SQL string to use, which should contain comma separated options.

:server

The server on which to run the query.

If a block is provided and :data option is not, this will yield to the block repeatedly. The block should return a string, or nil to signal that it is finished.

[show source]
    # File lib/sequel/adapters/postgres.rb
434 def copy_into(table, opts=OPTS)
435   data = opts[:data]
436   data = Array(data) if data.is_a?(String)
437 
438   if defined?(yield) && data
439     raise Error, "Cannot provide both a :data option and a block to copy_into"
440   elsif !defined?(yield) && !data
441     raise Error, "Must provide either a :data option or a block to copy_into"
442   end
443 
444   synchronize(opts[:server]) do |conn|
445     conn.execute(copy_into_sql(table, opts))
446     begin
447       if defined?(yield)
448         while buf = yield
449           conn.put_copy_data(buf)
450         end
451       else
452         data.each{|buff| conn.put_copy_data(buff)}
453       end
454     rescue Exception => e
455       conn.put_copy_end("ruby exception occurred while copying data into PostgreSQL")
456     ensure
457       conn.put_copy_end unless e
458       while res = conn.get_result
459         raise e if e
460         check_database_errors{res.check}
461       end
462     end
463   end 
464 end
copy_table(table, opts=OPTS)

simplecov:enable copy_table uses PostgreSQL’s +COPY TO STDOUT+ SQL statement to return formatted results directly to the caller. This method is only supported if pg is the underlying ruby driver. This method should only be called if you want results returned to the client. If you are using +COPY TO+ with a filename, you should just use run instead of this method.

The table argument supports the following types:

String

Uses the first argument directly as literal SQL. If you are using a version of PostgreSQL before 9.0, you will probably want to use a string if you are using any options at all, as the syntax Sequel uses for options is only compatible with PostgreSQL 9.0+. This should be the full COPY statement passed to PostgreSQL, not just the SELECT query. If a string is given, the :format and :options options are ignored.

Dataset

Uses a query instead of a table name when copying.

other

Uses a table name (usually a symbol) when copying.

The following options are respected:

:format

The format to use. The PostgreSQL default is text, possible options are :csv, :json, or :binary.

:options

An options SQL string to use, which should contain comma separated options.

:server

The server on which to run the query.

If a block is provided, the method continually yields to the block, one yield per row. If a block is not provided, a single string is returned with all of the data.

[show source]
    # File lib/sequel/adapters/postgres.rb
382 def copy_table(table, opts=OPTS)
383   synchronize(opts[:server]) do |conn|
384     sql = copy_table_sql(table, opts)
385     check_database_errors{conn.execute(sql)}
386 
387     begin
388       if defined?(yield)
389         while buf = conn.get_copy_data
390           yield buf
391         end
392         b = nil
393       else
394         b = String.new
395         b << buf while buf = conn.get_copy_data
396       end
397 
398       res = conn.get_last_result
399       if !res || res.result_status != 1
400         raise PG::NotAllCopyDataRetrieved, "Not all COPY data retrieved"
401       end
402 
403       b
404     rescue => e
405       raise_error(e, :disconnect=>true)
406     ensure
407       if buf && !e
408         raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state"
409       end
410     end
411   end 
412 end
disconnect_connection(conn)
[show source]
    # File lib/sequel/adapters/postgres.rb
292 def disconnect_connection(conn)
293   conn.finish
294 rescue PGError, IOError
295   nil
296 end
error_info(e)

simplecov:enable Return a hash of information about the related PGError (or Sequel::DatabaseError that wraps a PGError), with the following entries (any of which may be nil):

:schema

The schema name related to the error

:table

The table name related to the error

:column

the column name related to the error

:constraint

The constraint name related to the error

:type

The datatype name related to the error

:severity

The severity of the error (e.g. “ERROR”)

:sql_state

The SQL state code related to the error

:message_primary

A single line message related to the error

:message_detail

Any detail supplementing the primary message

:message_hint

Possible suggestion about how to fix the problem

:statement_position

Character offset in statement submitted by client where error occurred (starting at 1)

:internal_position

Character offset in internal statement where error occurred (starting at 1)

:internal_query

Text of internally-generated statement where error occurred

:source_file

PostgreSQL source file where the error occurred

:source_line

Line number of PostgreSQL source file where the error occurred

:source_function

Function in PostgreSQL source file where the error occurred

This requires a PostgreSQL 9.3+ server and 9.3+ client library, and ruby-pg 0.16.0+ to be supported.

[show source]
    # File lib/sequel/adapters/postgres.rb
323 def error_info(e)
324   e = e.wrapped_exception if e.is_a?(DatabaseError)
325   r = e.result
326   {
327     :schema => r.error_field(::PG::PG_DIAG_SCHEMA_NAME),
328     :table => r.error_field(::PG::PG_DIAG_TABLE_NAME),
329     :column => r.error_field(::PG::PG_DIAG_COLUMN_NAME),
330     :constraint => r.error_field(::PG::PG_DIAG_CONSTRAINT_NAME),
331     :type => r.error_field(::PG::PG_DIAG_DATATYPE_NAME),
332     :severity => r.error_field(::PG::PG_DIAG_SEVERITY),
333     :sql_state => r.error_field(::PG::PG_DIAG_SQLSTATE),
334     :message_primary => r.error_field(::PG::PG_DIAG_MESSAGE_PRIMARY),
335     :message_detail => r.error_field(::PG::PG_DIAG_MESSAGE_DETAIL),
336     :message_hint => r.error_field(::PG::PG_DIAG_MESSAGE_HINT),
337     :statement_position => r.error_field(::PG::PG_DIAG_STATEMENT_POSITION),
338     :internal_position => r.error_field(::PG::PG_DIAG_INTERNAL_POSITION),
339     :internal_query => r.error_field(::PG::PG_DIAG_INTERNAL_QUERY),
340     :source_file => r.error_field(::PG::PG_DIAG_SOURCE_FILE),
341     :source_line => r.error_field(::PG::PG_DIAG_SOURCE_LINE),
342     :source_function => r.error_field(::PG::PG_DIAG_SOURCE_FUNCTION)
343   }
344 end
execute(sql, opts=OPTS, &block)
[show source]
    # File lib/sequel/adapters/postgres.rb
347 def execute(sql, opts=OPTS, &block)
348   synchronize(opts[:server]){|conn| check_database_errors{_execute(conn, sql, opts, &block)}}
349 end
listen(channels, opts=OPTS, &block)

Listens on the given channel (or multiple channels if channel is an array), waiting for notifications. After a notification is received, or the timeout has passed, stops listening to the channel. Options:

:after_listen

An object that responds to call that is called with the underlying connection after the LISTEN statement is sent, but before the connection starts waiting for notifications.

:loop

Whether to continually wait for notifications, instead of just waiting for a single notification. If this option is given, a block must be provided. If this object responds to call, it is called with the underlying connection after each notification is received (after the block is called). If a :timeout option is used, and a callable object is given, the object will also be called if the timeout expires. If :loop is used and you want to stop listening, you can either break from inside the block given to listen, or you can throw :stop from inside the :loop object’s call method or the block.

:server

The server on which to listen, if the sharding support is being used.

:timeout

How long to wait for a notification, in seconds (can provide a float value for fractional seconds). If this object responds to call, it will be called and should return the number of seconds to wait. If the loop option is also specified, the object will be called on each iteration to obtain a new timeout value. If not given or nil, waits indefinitely.

This method is only supported if pg is used as the underlying ruby driver. It returns the channel the notification was sent to (as a string), unless :loop was used, in which case it returns nil. If a block is given, it is yielded 3 arguments:

  • the channel the notification was sent to (as a string)

  • the backend pid of the notifier (as an integer),

  • and the payload of the notification (as a string or nil).

[show source]
    # File lib/sequel/adapters/postgres.rb
489 def listen(channels, opts=OPTS, &block)
490   check_database_errors do
491     synchronize(opts[:server]) do |conn|
492       begin
493         channels = Array(channels)
494         channels.each do |channel|
495           sql = "LISTEN ".dup
496           dataset.send(:identifier_append, sql, channel)
497           conn.execute(sql)
498         end
499         opts[:after_listen].call(conn) if opts[:after_listen]
500         timeout = opts[:timeout]
501         if timeout
502           timeout_block = timeout.respond_to?(:call) ? timeout : proc{timeout}
503         end
504 
505         if l = opts[:loop]
506           raise Error, 'calling #listen with :loop requires a block' unless block
507           loop_call = l.respond_to?(:call)
508           catch(:stop) do
509             while true
510               t = timeout_block ? [timeout_block.call] : []
511               conn.wait_for_notify(*t, &block)
512               l.call(conn) if loop_call
513             end
514           end
515           nil
516         else
517           t = timeout_block ? [timeout_block.call] : []
518           conn.wait_for_notify(*t, &block)
519         end
520       ensure
521         conn.execute("UNLISTEN *")
522         true while conn.wait_for_notify(0)
523       end
524     end
525   end
526 end