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