class Sequel::Postgres::Database

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

def check_database_errors

Convert exceptions raised from the block into DatabaseErrors.
def check_database_errors
  begin
    yield
  rescue => e
    raise_error(e, :classes=>CONVERTED_EXCEPTIONS)
  end
end

def connect(server)

driver is used.
sslmode. :connect_timeout and :ssl_mode are only supported if the pg
connection timeout in seconds, and :sslmode sets whether postgres's
client encoding for the connection, :connect_timeout is a
options, using the :encoding or :charset option changes the
Connects to the database. In addition to the standard database
def connect(server)
  opts = server_opts(server)
  conn = if SEQUEL_POSTGRES_USES_PG
    connection_params = {
      :host => opts[:host],
      :port => opts[:port] || 5432,
      :dbname => opts[:database],
      :user => opts[:user],
      :password => opts[:password],
      :connect_timeout => opts[:connect_timeout] || 20,
      :sslmode => opts[:sslmode]
    }.delete_if { |key, value| blank_object?(value) }
    Adapter.connect(connection_params)
  else
    Adapter.connect(
      (opts[:host] unless blank_object?(opts[:host])),
      opts[:port] || 5432,
      nil, '',
      opts[:database],
      opts[:user],
      opts[:password]
    )
  end
  if encoding = opts[:encoding] || opts[:charset]
    if conn.respond_to?(:set_client_encoding)
      conn.set_client_encoding(encoding)
    else
      conn.async_exec("set client_encoding to '#{encoding}'")
    end
  end
  conn.db = self
  conn.apply_connection_settings
  @conversion_procs ||= get_conversion_procs(conn)
  conn
end

def copy_table(table, opts={})

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

:server :: The server on which to run the query.
:options :: An options SQL string to use, which should contain comma separated options.
:format :: The format to use. text is the default, so this should be :csv or :binary.

The following options are respected:

other :: Uses a table name (usually a symbol) when copying.
Dataset :: Uses a query instead of a table name when copying.
Sequel uses for options is only compatible with PostgreSQL 9.0+.
use a string if you are using any options at all, as the syntax
a version of PostgreSQL before 9.0, you will probably want to
String :: Uses the first argument directly as literal SQL. If you are using

The table argument supports the following types:

in the future.
method does not currently support +COPY FROM STDIN+, but that may be supported
with a filename, you should just use +run+ instead of this method. This
results returned to the client. If you are using +COPY FROM+ or +COPY TO+
underlying ruby driver. This method should only be called if you want
results directly to the caller. This method is only supported if pg is the
+copy_table+ uses PostgreSQL's +COPY+ SQL statement to return formatted
def copy_table(table, opts={})
  sql = if table.is_a?(String)
    sql = table
  else
    if opts[:options] || opts[:format]
      options = " ("
      options << "FORMAT #{opts[:format]}" if opts[:format]
      options << "#{', ' if opts[:format]}#{opts[:options]}" if opts[:options]
      options << ')'
    end
    table = if table.is_a?(::Sequel::Dataset)
      "(#{table.sql})"
    else
      literal(table)
    end
   sql = "COPY #{table} TO STDOUT#{options}"
  end
  synchronize(opts[:server]) do |conn| 
    conn.execute(sql)
    begin
      if block_given?
        while buf = conn.get_copy_data
          yield buf
        end
        nil
      else
        b = ''
        b << buf while buf = conn.get_copy_data
        b
      end
    ensure
      raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state" if buf
    end
  end 
end

def disconnect_connection(conn)

Disconnect given connection
def disconnect_connection(conn)
  begin
    conn.finish
  rescue PGError
  end
end

def execute(sql, opts={}, &block)

Execute the given SQL with the given args on an available connection.
def execute(sql, opts={}, &block)
  check_database_errors do
    return execute_prepared_statement(sql, opts, &block) if Symbol === sql
    synchronize(opts[:server]){|conn| conn.execute(sql, opts[:arguments], &block)}
  end
end

def execute_insert(sql, opts={})

automatically generated).
Insert the values into the table and return the primary key (if
def execute_insert(sql, opts={})
  return execute(sql, opts) if Symbol === sql
  check_database_errors do
    synchronize(opts[:server]) do |conn|
      conn.execute(sql, opts[:arguments])
      insert_result(conn, opts[:table], opts[:values])
    end
  end
end

def execute_prepared_statement(name, opts={})

of the primary key for the last inserted row.
of rows changed. If the :insert option is passed, return the value
If a block is given, yield the result, otherwise, return the number
deallocate that statement first and then prepare this statement.
has prepared a statement with the same name and different SQL,
a statement with the given name yet, prepare it. If the connection
connection, using the given args. If the connection has not prepared
Execute the prepared statement with the given name on an available
def execute_prepared_statement(name, opts={})
  ps = prepared_statements[name]
  sql = ps.prepared_sql
  ps_name = name.to_s
  args = opts[:arguments]
  synchronize(opts[:server]) do |conn|
    unless conn.prepared_statements[ps_name] == sql
      if conn.prepared_statements.include?(ps_name)
        conn.execute("DEALLOCATE #{ps_name}") unless conn.prepared_statements[ps_name] == sql
      end
      conn.prepared_statements[ps_name] = sql
      conn.check_disconnect_errors{log_yield("PREPARE #{ps_name} AS #{sql}"){conn.prepare(ps_name, sql)}}
    end
    q = conn.check_disconnect_errors{log_yield("EXECUTE #{ps_name}", args){conn.exec_prepared(ps_name, args)}}
    if opts[:table] && opts[:values]
      insert_result(conn, opts[:table], opts[:values])
    else
      begin
        block_given? ? yield(q) : q.cmd_tuples
      ensure
        q.clear
      end
    end
  end
end

def get_conversion_procs(conn)

Return the conversion procs hash to use for this database
def get_conversion_procs(conn)
  procs = PG_TYPES.dup
  procs[1114] = method(:to_application_timestamp)
  procs[1184] = method(:to_application_timestamp)
  conn.execute("SELECT oid, typname FROM pg_type where typtype = 'b'") do |res|
    res.ntuples.times do |recnum|
      if pr = PG_NAMED_TYPES[res.getvalue(recnum, 1).untaint.to_sym]
        procs[res.getvalue(recnum, 0).to_i] ||= pr
      end
    end
  end
  procs
end

def initialize(*args)

so we can get the correct return values for inserted rows.
Add the primary_keys and primary_key_sequences instance variables,
def initialize(*args)
  super
  @primary_keys = {}
  @primary_key_sequences = {}
end

def listen(channels, opts={}, &block)

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

fractional seconds). If not given or nil, waits indefinitely.
:timeout :: How long to wait for a notification, in seconds (can provide a float value for
:server :: The server on which to listen, if the sharding support is being used.
block given to #listen, or you can throw :stop from inside the :loop object's call method or the block.
timeout expires. If :loop is used and you want to stop listening, you can either break from inside the
If a :timeout option is used, and a callable object is given, the object will also be called if the
called with the underlying connection after each notification is received (after the block is called).
notification. If this option is given, a block must be provided. If this object responds to call, it is
:loop :: Whether to continually wait for notifications, instead of just waiting for a single
statement is sent, but before the connection starts waiting for notifications.
:after_listen :: An object that responds to +call+ that is called with the underlying connection after the LISTEN

After a notification is received, or the timeout has passed, stops listening to the channel. Options:
Listens on the given channel (or multiple channels if channel is an array), waiting for notifications.
def listen(channels, opts={}, &block)
  check_database_errors do
    synchronize(opts[:server]) do |conn|
      begin
        channels = Array(channels)
        channels.each{|channel| conn.execute("LISTEN #{channel}")}
        opts[:after_listen].call(conn) if opts[:after_listen]
        timeout = opts[:timeout] ? [opts[:timeout]] : []
        if l = opts[:loop]
          raise Error, 'calling #listen with :loop requires a block' unless block
          loop_call = l.respond_to?(:call)
          catch(:stop) do
            loop do
              conn.wait_for_notify(*timeout, &block)
              l.call(conn) if loop_call
            end
          end
          nil
        else
          conn.wait_for_notify(*timeout, &block)
        end
      ensure
        conn.execute("UNLISTEN *")
      end
    end
  end
end