Method: Sequel::Dataset#import
- Defined in:
- lib/sequel/dataset/actions.rb
#import(columns, values, opts = OPTS) ⇒ Object
Inserts multiple records into the associated table. This method can be used to efficiently insert a large number of records into a table in a single query if the database supports it. Inserts are automatically wrapped in a transaction if necessary.
This method is called with a columns array and an array of value arrays:
DB[:table].import([:x, :y], [[1, 2], [3, 4]])
# INSERT INTO table (x, y) VALUES (1, 2)
# INSERT INTO table (x, y) VALUES (3, 4)
or, if the database supports it:
# INSERT INTO table (x, y) VALUES (1, 2), (3, 4)
This method also accepts a dataset instead of an array of value arrays:
DB[:table].import([:x, :y], DB[:table2].select(:a, :b))
# INSERT INTO table (x, y) SELECT a, b FROM table2
The return value of this method is undefined and should not be used, except in two cases:
-
When the
return: :primary_keyoption is used. -
On PostgreSQL, when the dataset uses RETURNING. In this case, if a single value is returned per row, the return value is an array of those values. If multiple values are returned per row, the return value is an array of hashes.
Options:
- :commit_every
-
Open a new transaction for every given number of records. For example, if you provide a value of 50, will commit after every 50 records. When a transaction is not required, this option controls the maximum number of values to insert with a single statement; it does not force the use of a transaction.
- :return
-
When this is set to :primary_key, returns an array of autoincremented primary key values for the rows inserted. This does not have an effect if
valuesis a Dataset. - :server
-
Set the server/shard to use for the transaction and insert queries.
- :skip_transaction
-
Do not use a transaction even when using multiple INSERT queries.
- :slice
-
Same as :commit_every, :commit_every takes precedence.
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/sequel/dataset/actions.rb', line 400 def import(columns, values, opts=OPTS) return insert(columns, values) if values.is_a?(Dataset) return if values.empty? raise(Error, 'Using Sequel::Dataset#import with an empty column array is not allowed') if columns.empty? ds = opts[:server] ? server(opts[:server]) : self if slice_size = opts.fetch(:commit_every, opts.fetch(:slice, default_import_slice)) offset = 0 rows = [] while offset < values.length rows << ds._import(columns, values[offset, slice_size], opts) offset += slice_size end rows.flatten else ds._import(columns, values, opts) end end |