Method: Sequel::Postgres::Database#copy_table

Defined in:
lib/sequel/adapters/postgres.rb

#copy_table(table, opts = OPTS) ⇒ Object

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



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/sequel/adapters/postgres.rb', line 381

def copy_table(table, opts=OPTS)
  synchronize(opts[:server]) do |conn|
    conn.execute(copy_table_sql(table, opts))
    begin
      if defined?(yield)
        while buf = conn.get_copy_data
          yield buf
        end
        b = nil
      else
        b = String.new
        b << buf while buf = conn.get_copy_data
      end

      res = conn.get_last_result
      if !res || res.result_status != 1
        raise PG::NotAllCopyDataRetrieved, "Not all COPY data retrieved"
      end

      b
    rescue => e
      raise_error(e, :disconnect=>true)
    ensure
      if buf && !e
        raise DatabaseDisconnectError, "disconnecting as a partial COPY may leave the connection in an unusable state"
      end
    end
  end 
end