Class Sequel::Postgres::Database
In: lib/sequel/adapters/postgres.rb
Parent: Sequel::Database

Database class for PostgreSQL databases used with Sequel and the pg, postgres, or postgres-pr driver.

Methods

Included Modules

Sequel::Postgres::DatabaseMethods

Constants

INFINITE_TIMESTAMP_STRINGS = ['infinity'.freeze, '-infinity'.freeze].freeze
INFINITE_DATETIME_VALUES = ([PLUS_INFINITY, MINUS_INFINITY] + INFINITE_TIMESTAMP_STRINGS).freeze

Attributes

convert_infinite_timestamps  [R]  Whether infinite timestamps/dates should be converted on retrieval. By default, no conversion is done, so an error is raised if you attempt to retrieve an infinite timestamp/date. You can set this to :nil to convert to nil, :string to leave as a string, or :float to convert to an infinite float.

Public Instance methods

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", and it won‘t ever handle Sequel::SQLTime values correctly. Only public for use by the adapter, shouldn‘t be used by external code.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 204
204:       def bound_variable_arg(arg, conn)
205:         case arg
206:         when Sequel::SQL::Blob
207:           {:value=>arg, :type=>17, :format=>1}
208:         when Sequel::SQLTime
209:           literal(arg)
210:         when DateTime, Time
211:           literal(arg)
212:         else
213:           arg
214:         end
215:       end

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, :ssl_mode, and :notice_receiver are only supported if the pg driver is used.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 224
224:       def connect(server)
225:         opts = server_opts(server)
226:         if SEQUEL_POSTGRES_USES_PG
227:           connection_params = {
228:             :host => opts[:host],
229:             :port => opts[:port] || 5432,
230:             :dbname => opts[:database],
231:             :user => opts[:user],
232:             :password => opts[:password],
233:             :connect_timeout => opts[:connect_timeout] || 20,
234:             :sslmode => opts[:sslmode]
235:           }.delete_if { |key, value| blank_object?(value) }
236:           conn = Adapter.connect(connection_params)
237: 
238:           conn.instance_variable_set(:@prepared_statements, {})
239: 
240:           if receiver = opts[:notice_receiver]
241:             conn.set_notice_receiver(&receiver)
242:           end
243:         else
244:           conn = Adapter.connect(
245:             (opts[:host] unless blank_object?(opts[:host])),
246:             opts[:port] || 5432,
247:             nil, '',
248:             opts[:database],
249:             opts[:user],
250:             opts[:password]
251:           )
252:         end
253: 
254:         conn.instance_variable_set(:@db, self)
255: 
256:         if encoding = opts[:encoding] || opts[:charset]
257:           if conn.respond_to?(:set_client_encoding)
258:             conn.set_client_encoding(encoding)
259:           else
260:             conn.async_exec("set client_encoding to '#{encoding}'")
261:           end
262:         end
263: 
264:         connection_configuration_sqls.each{|sql| conn.execute(sql)}
265:         conn
266:       end

Set whether to allow infinite timestamps/dates. Make sure the conversion proc for date reflects that setting.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 270
270:       def convert_infinite_timestamps=(v)
271:         @convert_infinite_timestamps = case v
272:         when Symbol
273:           v
274:         when 'nil'
275:           :nil
276:         when 'string'
277:           :string
278:         when 'float'
279:           :float
280:         when String
281:           typecast_value_boolean(v)
282:         else
283:           false
284:         end
285: 
286:         pr = old_pr = @use_iso_date_format ? TYPE_TRANSLATOR.method(:date) : Sequel.method(:string_to_date)
287:         if v
288:           pr = lambda do |val|
289:             case val
290:             when *INFINITE_TIMESTAMP_STRINGS
291:               infinite_timestamp_value(val)
292:             else
293:               old_pr.call(val)
294:             end
295:           end
296:         end
297:         conversion_procs[1082] = pr
298:       end

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.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 403
403:         def copy_into(table, opts=OPTS)
404:           data = opts[:data]
405:           data = Array(data) if data.is_a?(String)
406: 
407:           if block_given? && data
408:             raise Error, "Cannot provide both a :data option and a block to copy_into"
409:           elsif !block_given? && !data
410:             raise Error, "Must provide either a :data option or a block to copy_into"
411:           end
412: 
413:           synchronize(opts[:server]) do |conn|
414:             conn.execute(copy_into_sql(table, opts))
415:             begin
416:               if block_given?
417:                 while buf = yield
418:                   conn.put_copy_data(buf)
419:                 end
420:               else
421:                 data.each{|buff| conn.put_copy_data(buff)}
422:               end
423:             rescue Exception => e
424:               conn.put_copy_end("ruby exception occurred while copying data into PostgreSQL")
425:             ensure
426:               conn.put_copy_end unless e
427:               while res = conn.get_result
428:                 raise e if e
429:                 check_database_errors{res.check}
430:               end
431:             end
432:           end 
433:         end

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+.
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. 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, 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.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 363
363:         def copy_table(table, opts=OPTS)
364:           synchronize(opts[:server]) do |conn|
365:             conn.execute(copy_table_sql(table, opts))
366:             begin
367:               if block_given?
368:                 while buf = conn.get_copy_data
369:                   yield buf
370:                 end
371:                 nil
372:               else
373:                 b = ''
374:                 b << buf while buf = conn.get_copy_data
375:                 b
376:               end
377:             ensure
378:               raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" if buf
379:             end
380:           end 
381:         end

Disconnect given connection

[Source]

     # File lib/sequel/adapters/postgres.rb, line 301
301:       def disconnect_connection(conn)
302:         begin
303:           conn.finish
304:         rescue PGError, IOError
305:         end
306:       end

Return a hash of information about the related PGError (or Sequel::DatabaseError that wraps a PGError), with the following entries:

: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

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

[Source]

     # File lib/sequel/adapters/postgres.rb, line 320
320:         def error_info(e)
321:           e = e.wrapped_exception if e.is_a?(DatabaseError)
322:           r = e.result
323:           h = {}
324:           h[:schema] = r.error_field(::PG::PG_DIAG_SCHEMA_NAME)
325:           h[:table] = r.error_field(::PG::PG_DIAG_TABLE_NAME)
326:           h[:column] = r.error_field(::PG::PG_DIAG_COLUMN_NAME)
327:           h[:constraint] = r.error_field(::PG::PG_DIAG_CONSTRAINT_NAME)
328:           h[:type] = r.error_field(::PG::PG_DIAG_DATATYPE_NAME)
329:           h
330:         end

Execute the given SQL with the given args on an available connection.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 334
334:       def execute(sql, opts=OPTS, &block)
335:         synchronize(opts[:server]){|conn| check_database_errors{_execute(conn, sql, opts, &block)}}
336:       end

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 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).

[Source]

     # File lib/sequel/adapters/postgres.rb, line 456
456:         def listen(channels, opts=OPTS, &block)
457:           check_database_errors do
458:             synchronize(opts[:server]) do |conn|
459:               begin
460:                 channels = Array(channels)
461:                 channels.each do |channel|
462:                   sql = "LISTEN "
463:                   dataset.send(:identifier_append, sql, channel)
464:                   conn.execute(sql)
465:                 end
466:                 opts[:after_listen].call(conn) if opts[:after_listen]
467:                 timeout = opts[:timeout] ? [opts[:timeout]] : []
468:                 if l = opts[:loop]
469:                   raise Error, 'calling #listen with :loop requires a block' unless block
470:                   loop_call = l.respond_to?(:call)
471:                   catch(:stop) do
472:                     loop do
473:                       conn.wait_for_notify(*timeout, &block)
474:                       l.call(conn) if loop_call
475:                     end
476:                   end
477:                   nil
478:                 else
479:                   conn.wait_for_notify(*timeout, &block)
480:                 end
481:               ensure
482:                 conn.execute("UNLISTEN *")
483:               end
484:             end
485:           end
486:         end

If convert_infinite_timestamps is true and the value is infinite, return an appropriate value based on the convert_infinite_timestamps setting.

[Source]

     # File lib/sequel/adapters/postgres.rb, line 491
491:       def to_application_timestamp(value)
492:         if convert_infinite_timestamps
493:           case value
494:           when *INFINITE_TIMESTAMP_STRINGS
495:             infinite_timestamp_value(value)
496:           else
497:             super
498:           end
499:         else
500:           super
501:         end
502:       end

[Validate]