activerecord-import 0.17.2 → 1.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (52) hide show
  1. checksums.yaml +5 -5
  2. data/.gitignore +1 -0
  3. data/.travis.yml +40 -23
  4. data/CHANGELOG.md +315 -1
  5. data/Gemfile +23 -13
  6. data/LICENSE +21 -56
  7. data/README.markdown +564 -33
  8. data/Rakefile +2 -1
  9. data/activerecord-import.gemspec +3 -3
  10. data/benchmarks/lib/cli_parser.rb +2 -1
  11. data/benchmarks/schema/{mysql_schema.rb → mysql2_schema.rb} +0 -0
  12. data/gemfiles/5.1.gemfile +2 -0
  13. data/gemfiles/5.2.gemfile +2 -0
  14. data/gemfiles/6.0.gemfile +2 -0
  15. data/gemfiles/6.1.gemfile +1 -0
  16. data/lib/activerecord-import.rb +2 -15
  17. data/lib/activerecord-import/adapters/abstract_adapter.rb +9 -3
  18. data/lib/activerecord-import/adapters/mysql_adapter.rb +17 -11
  19. data/lib/activerecord-import/adapters/postgresql_adapter.rb +68 -20
  20. data/lib/activerecord-import/adapters/sqlite3_adapter.rb +128 -9
  21. data/lib/activerecord-import/base.rb +12 -7
  22. data/lib/activerecord-import/import.rb +514 -166
  23. data/lib/activerecord-import/synchronize.rb +2 -2
  24. data/lib/activerecord-import/value_sets_parser.rb +16 -0
  25. data/lib/activerecord-import/version.rb +1 -1
  26. data/test/adapters/makara_postgis.rb +1 -0
  27. data/test/import_test.rb +274 -23
  28. data/test/makara_postgis/import_test.rb +8 -0
  29. data/test/models/account.rb +3 -0
  30. data/test/models/animal.rb +6 -0
  31. data/test/models/bike_maker.rb +7 -0
  32. data/test/models/tag.rb +1 -1
  33. data/test/models/topic.rb +14 -0
  34. data/test/models/user.rb +3 -0
  35. data/test/models/user_token.rb +4 -0
  36. data/test/schema/generic_schema.rb +30 -8
  37. data/test/schema/mysql2_schema.rb +19 -0
  38. data/test/schema/postgresql_schema.rb +18 -0
  39. data/test/schema/sqlite3_schema.rb +13 -0
  40. data/test/support/factories.rb +9 -8
  41. data/test/support/generate.rb +6 -6
  42. data/test/support/mysql/import_examples.rb +14 -2
  43. data/test/support/postgresql/import_examples.rb +220 -1
  44. data/test/support/shared_examples/on_duplicate_key_ignore.rb +15 -9
  45. data/test/support/shared_examples/on_duplicate_key_update.rb +271 -8
  46. data/test/support/shared_examples/recursive_import.rb +91 -21
  47. data/test/support/sqlite3/import_examples.rb +189 -25
  48. data/test/synchronize_test.rb +8 -0
  49. data/test/test_helper.rb +24 -3
  50. data/test/value_sets_bytes_parser_test.rb +13 -2
  51. metadata +32 -13
  52. data/test/schema/mysql_schema.rb +0 -16
data/LICENSE CHANGED
@@ -1,56 +1,21 @@
1
- Ruby is copyrighted free software by Yukihiro Matsumoto <matz@netlab.jp>.
2
- You can redistribute it and/or modify it under either the terms of the
3
- 2-clause BSDL (see the file BSDL), or the conditions below:
4
-
5
- 1. You may make and give away verbatim copies of the source form of the
6
- software without restriction, provided that you duplicate all of the
7
- original copyright notices and associated disclaimers.
8
-
9
- 2. You may modify your copy of the software in any way, provided that
10
- you do at least ONE of the following:
11
-
12
- a) place your modifications in the Public Domain or otherwise
13
- make them Freely Available, such as by posting said
14
- modifications to Usenet or an equivalent medium, or by allowing
15
- the author to include your modifications in the software.
16
-
17
- b) use the modified software only within your corporation or
18
- organization.
19
-
20
- c) give non-standard binaries non-standard names, with
21
- instructions on where to get the original software distribution.
22
-
23
- d) make other distribution arrangements with the author.
24
-
25
- 3. You may distribute the software in object code or binary form,
26
- provided that you do at least ONE of the following:
27
-
28
- a) distribute the binaries and library files of the software,
29
- together with instructions (in the manual page or equivalent)
30
- on where to get the original distribution.
31
-
32
- b) accompany the distribution with the machine-readable source of
33
- the software.
34
-
35
- c) give non-standard binaries non-standard names, with
36
- instructions on where to get the original software distribution.
37
-
38
- d) make other distribution arrangements with the author.
39
-
40
- 4. You may modify and include the part of the software into any other
41
- software (possibly commercial). But some files in the distribution
42
- are not written by the author, so that they are not under these terms.
43
-
44
- For the list of those files and their copying conditions, see the
45
- file LEGAL.
46
-
47
- 5. The scripts and library files supplied as input to or produced as
48
- output from the software do not automatically fall under the
49
- copyright of the software, but belong to whomever generated them,
50
- and may be sold commercially, and may be aggregated with this
51
- software.
52
-
53
- 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
54
- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
55
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
56
- PURPOSE.
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Zach Dennis <zach.dennis@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.markdown CHANGED
@@ -1,6 +1,6 @@
1
- # activerecord-import [![Build Status](https://travis-ci.org/zdennis/activerecord-import.svg?branch=master)](https://travis-ci.org/zdennis/activerecord-import)
1
+ # Activerecord-Import [![Build Status](https://travis-ci.org/zdennis/activerecord-import.svg?branch=master)](https://travis-ci.org/zdennis/activerecord-import)
2
2
 
3
- activerecord-import is a library for bulk inserting data using ActiveRecord.
3
+ Activerecord-Import is a library for bulk inserting data using ActiveRecord.
4
4
 
5
5
  One of its major features is following activerecord associations and generating the minimal
6
6
  number of SQL insert statements required, avoiding the N+1 insert problem. An example probably
@@ -21,47 +21,531 @@ and then the reviews:
21
21
  That would be about 4M SQL insert statements vs 3, which results in vastly improved performance. In our case, it converted
22
22
  an 18 hour batch process to <2 hrs.
23
23
 
24
- ### Rails 5.0
24
+ The gem provides the following high-level features:
25
+
26
+ * Works with raw columns and arrays of values (fastest)
27
+ * Works with model objects (faster)
28
+ * Performs validations (fast)
29
+ * Performs on duplicate key updates (requires MySQL, SQLite 3.24.0+, or Postgres 9.5+)
30
+
31
+ ## Table of Contents
32
+
33
+ * [Examples](#examples)
34
+ * [Introduction](#introduction)
35
+ * [Columns and Arrays](#columns-and-arrays)
36
+ * [Hashes](#hashes)
37
+ * [ActiveRecord Models](#activerecord-models)
38
+ * [Batching](#batching)
39
+ * [Recursive](#recursive)
40
+ * [Options](#options)
41
+ * [Duplicate Key Ignore](#duplicate-key-ignore)
42
+ * [Duplicate Key Update](#duplicate-key-update)
43
+ * [Return Info](#return-info)
44
+ * [Counter Cache](#counter-cache)
45
+ * [ActiveRecord Timestamps](#activerecord-timestamps)
46
+ * [Callbacks](#callbacks)
47
+ * [Supported Adapters](#supported-adapters)
48
+ * [Additional Adapters](#additional-adapters)
49
+ * [Requiring](#requiring)
50
+ * [Autoloading via Bundler](#autoloading-via-bundler)
51
+ * [Manually Loading](#manually-loading)
52
+ * [Load Path Setup](#load-path-setup)
53
+ * [Conflicts With Other Gems](#conflicts-with-other-gems)
54
+ * [More Information](#more-information)
55
+ * [Contributing](#contributing)
56
+ * [Running Tests](#running-tests)
57
+ * [Issue Triage](#issue-triage)
58
+
59
+ ### Examples
60
+
61
+ #### Introduction
62
+
63
+ This gem adds an `import` method (or `bulk_import`, for compatibility with gems like `elasticsearch-model`; see [Conflicts With Other Gems](#conflicts-with-other-gems)) to ActiveRecord classes.
64
+
65
+ Without `activerecord-import`, you'd write something like this:
25
66
 
26
- Use activerecord-import 0.11.0 or higher.
67
+ ```ruby
68
+ 10.times do |i|
69
+ Book.create! name: "book #{i}"
70
+ end
71
+ ```
27
72
 
28
- ### Rails 4.0
73
+ This would end up making 10 SQL calls. YUCK! With `activerecord-import`, you can instead do this:
29
74
 
30
- Use activerecord-import 0.4.0 or higher.
75
+ ```ruby
76
+ books = []
77
+ 10.times do |i|
78
+ books << Book.new(name: "book #{i}")
79
+ end
80
+ Book.import books # or use import!
81
+ ```
31
82
 
32
- ### Rails 3.2.x up to, but not including 4.0
83
+ and only have 1 SQL call. Much better!
33
84
 
34
- Use activerecord-import 0.3.0 or higher.
85
+ #### Columns and Arrays
86
+
87
+ The `import` method can take an array of column names (string or symbols) and an array of arrays. Each child array represents an individual record and its list of values in the same order as the columns. This is the fastest import mechanism and also the most primitive.
88
+
89
+ ```ruby
90
+ columns = [ :title, :author ]
91
+ values = [ ['Book1', 'George Orwell'], ['Book2', 'Bob Jones'] ]
35
92
 
36
- ### Rails 3.1.x up to, but not including 3.2
93
+ # Importing without model validations
94
+ Book.import columns, values, validate: false
37
95
 
38
- Use the latest in the activerecord-import 0.3.x series.
96
+ # Import with model validations
97
+ Book.import columns, values, validate: true
98
+
99
+ # when not specified :validate defaults to true
100
+ Book.import columns, values
101
+ ```
102
+
103
+ #### Hashes
104
+
105
+ The `import` method can take an array of hashes. The keys map to the column names in the database.
106
+
107
+ ```ruby
108
+ values = [{ title: 'Book1', author: 'George Orwell' }, { title: 'Book2', author: 'Bob Jones'}]
39
109
 
40
- ### Rails 3.0.x up to, but not including 3.1
110
+ # Importing without model validations
111
+ Book.import values, validate: false
112
+
113
+ # Import with model validations
114
+ Book.import values, validate: true
115
+
116
+ # when not specified :validate defaults to true
117
+ Book.import values
118
+ ```
119
+ #### Import Using Hashes and Explicit Column Names
120
+
121
+ The `import` method can take an array of column names and an array of hash objects. The column names are used to determine what fields of data should be imported. The following example will only import books with the `title` field:
122
+
123
+ ```ruby
124
+ books = [
125
+ { title: "Book 1", author: "George Orwell" },
126
+ { title: "Book 2", author: "Bob Jones" }
127
+ ]
128
+ columns = [ :title ]
129
+
130
+ # without validations
131
+ Book.import columns, books, validate: false
132
+
133
+ # with validations
134
+ Book.import columns, books, validate: true
135
+
136
+ # when not specified :validate defaults to true
137
+ Book.import columns, books
138
+
139
+ # result in table books
140
+ # title | author
141
+ #--------|--------
142
+ # Book 1 | NULL
143
+ # Book 2 | NULL
144
+
145
+ ```
41
146
 
42
- Use activerecord-import 0.2.11. As of activerecord-import 0.3.0 we are relying on functionality that was introduced in Rails 3.1. Since Rails 3.0.x is no longer a supported version of Rails we have decided to drop support as well.
147
+ Using hashes will only work if the columns are consistent in every hash of the array. If this does not hold, an exception will be raised. There are two workarounds: use the array to instantiate an array of ActiveRecord objects and then pass that into `import` or divide the array into multiple ones with consistent columns and import each one separately.
43
148
 
44
- ### More Information : Usage and Examples in Wiki
149
+ See https://github.com/zdennis/activerecord-import/issues/507 for discussion.
45
150
 
46
- For more information on activerecord-import please see its wiki: https://github.com/zdennis/activerecord-import/wiki
151
+ ```ruby
152
+ arr = [
153
+ { bar: 'abc' },
154
+ { baz: 'xyz' },
155
+ { bar: '123', baz: '456' }
156
+ ]
157
+
158
+ # An exception will be raised
159
+ Foo.import arr
160
+
161
+ # better
162
+ arr.map! { |args| Foo.new(args) }
163
+ Foo.import arr
164
+
165
+ # better
166
+ arr.group_by(&:keys).each_value do |v|
167
+ Foo.import v
168
+ end
169
+ ```
170
+
171
+ #### ActiveRecord Models
172
+
173
+ The `import` method can take an array of models. The attributes will be pulled off from each model by looking at the columns available on the model.
174
+
175
+ ```ruby
176
+ books = [
177
+ Book.new(title: "Book 1", author: "George Orwell"),
178
+ Book.new(title: "Book 2", author: "Bob Jones")
179
+ ]
180
+
181
+ # without validations
182
+ Book.import books, validate: false
183
+
184
+ # with validations
185
+ Book.import books, validate: true
186
+
187
+ # when not specified :validate defaults to true
188
+ Book.import books
189
+ ```
190
+
191
+ The `import` method can take an array of column names and an array of models. The column names are used to determine what fields of data should be imported. The following example will only import books with the `title` field:
192
+
193
+ ```ruby
194
+ books = [
195
+ Book.new(title: "Book 1", author: "George Orwell"),
196
+ Book.new(title: "Book 2", author: "Bob Jones")
197
+ ]
198
+ columns = [ :title ]
199
+
200
+ # without validations
201
+ Book.import columns, books, validate: false
202
+
203
+ # with validations
204
+ Book.import columns, books, validate: true
205
+
206
+ # when not specified :validate defaults to true
207
+ Book.import columns, books
208
+
209
+ # result in table books
210
+ # title | author
211
+ #--------|--------
212
+ # Book 1 | NULL
213
+ # Book 2 | NULL
214
+
215
+ ```
216
+
217
+ #### Batching
218
+
219
+ The `import` method can take a `batch_size` option to control the number of rows to insert per INSERT statement. The default is the total number of records being inserted so there is a single INSERT statement.
220
+
221
+ ```ruby
222
+ books = [
223
+ Book.new(title: "Book 1", author: "George Orwell"),
224
+ Book.new(title: "Book 2", author: "Bob Jones"),
225
+ Book.new(title: "Book 1", author: "John Doe"),
226
+ Book.new(title: "Book 2", author: "Richard Wright")
227
+ ]
228
+ columns = [ :title ]
229
+
230
+ # 2 INSERT statements for 4 records
231
+ Book.import columns, books, batch_size: 2
232
+ ```
233
+
234
+ If your import is particularly large or slow (possibly due to [callbacks](#callbacks)) whilst batch importing, you might want a way to report back on progress. This is supported by passing a callable as the `batch_progress` option. e.g:
235
+
236
+ ```ruby
237
+ my_proc = ->(rows_size, num_batches, current_batch_number, batch_duration_in_secs) {
238
+ # Using the arguments provided to the callable, you can
239
+ # send an email, post to a websocket,
240
+ # update slack, alert if import is taking too long, etc.
241
+ }
242
+
243
+ Book.import columns, books, batch_size: 2, batch_progress: my_proc
244
+ ```
245
+
246
+ #### Recursive
247
+
248
+ NOTE: This only works with PostgreSQL and ActiveRecord objects. This won't work with
249
+ hashes or arrays as recursive inputs.
250
+
251
+ Assume that Books <code>has_many</code> Reviews.
252
+
253
+ ```ruby
254
+ books = []
255
+ 10.times do |i|
256
+ book = Book.new(name: "book #{i}")
257
+ book.reviews.build(title: "Excellent")
258
+ books << book
259
+ end
260
+ Book.import books, recursive: true
261
+ ```
262
+
263
+ ### Options
264
+
265
+ Key | Options | Default | Description
266
+ ------------------------- | --------------------- | ------------------ | -----------
267
+ :validate | `true`/`false` | `true` | Whether or not to run `ActiveRecord` validations (uniqueness skipped). This option will always be true when using `import!`.
268
+ :validate_uniqueness | `true`/`false` | `false` | Whether or not to run uniqueness validations, has potential pitfalls, use with caution (requires `>= v0.27.0`).
269
+ :validate_with_context | `Symbol` |`:create`/`:update` | Allows passing an ActiveModel validation context for each model. Default is `:create` for new records and `:update` for existing ones.
270
+ :track_validation_failures| `true`/`false` | `false` | When this is set to true, `failed_instances` will be an array of arrays, with each inner array having the form `[:index_in_dataset, :object_with_errors]`
271
+ :on_duplicate_key_ignore | `true`/`false` | `false` | Allows skipping records with duplicate keys. See [here](https://github.com/zdennis/activerecord-import/#duplicate-key-ignore) for more details.
272
+ :ignore | `true`/`false` | `false` | Alias for :on_duplicate_key_ignore.
273
+ :on_duplicate_key_update | :all, `Array`, `Hash` | N/A | Allows upsert logic to be used. See [here](https://github.com/zdennis/activerecord-import/#duplicate-key-update) for more details.
274
+ :synchronize | `Array` | N/A | An array of ActiveRecord instances. This synchronizes existing instances in memory with updates from the import.
275
+ :timestamps | `true`/`false` | `true` | Enables/disables timestamps on imported records.
276
+ :recursive | `true`/`false` | `false` | Imports has_many/has_one associations (PostgreSQL only).
277
+ :batch_size | `Integer` | total # of records | Max number of records to insert per import
278
+ :raise_error | `true`/`false` | `false` | Raises an exception at the first invalid record. This means there will not be a result object returned. The `import!` method is a shortcut for this.
279
+ :all_or_none | `true`/`false` | `false` | Will not import any records if there is a record with validation errors.
280
+
281
+ #### Duplicate Key Ignore
282
+
283
+ [MySQL](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html), [SQLite](https://www.sqlite.org/lang_insert.html), and [PostgreSQL](https://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT) (9.5+) support `on_duplicate_key_ignore` which allows you to skip records if a primary or unique key constraint is violated.
284
+
285
+ For Postgres 9.5+ it adds `ON CONFLICT DO NOTHING`, for MySQL it uses `INSERT IGNORE`, and for SQLite it uses `INSERT OR IGNORE`. Cannot be enabled on a recursive import. For database adapters that normally support setting primary keys on imported objects, this option prevents that from occurring.
286
+
287
+ ```ruby
288
+ book = Book.create! title: "Book1", author: "George Orwell"
289
+ book.title = "Updated Book Title"
290
+ book.author = "Bob Barker"
291
+
292
+ Book.import [book], on_duplicate_key_ignore: true
293
+
294
+ book.reload.title # => "Book1" (stayed the same)
295
+ book.reload.author # => "George Orwell" (stayed the same)
296
+ ```
297
+
298
+ The option `:on_duplicate_key_ignore` is bypassed when `:recursive` is enabled for [PostgreSQL imports](https://github.com/zdennis/activerecord-import/wiki#recursive-example-postgresql-only).
299
+
300
+ #### Duplicate Key Update
301
+
302
+ MySQL, PostgreSQL (9.5+), and SQLite (3.24.0+) support `on duplicate key update` (also known as "upsert") which allows you to specify fields whose values should be updated if a primary or unique key constraint is violated.
303
+
304
+ One big difference between MySQL and PostgreSQL support is that MySQL will handle any conflict that happens, but PostgreSQL requires that you specify which columns the conflict would occur over. SQLite models its upsert support after PostgreSQL.
305
+
306
+ This will use MySQL's `ON DUPLICATE KEY UPDATE` or Postgres/SQLite `ON CONFLICT DO UPDATE` to do upsert.
307
+
308
+ Basic Update
309
+
310
+ ```ruby
311
+ book = Book.create! title: "Book1", author: "George Orwell"
312
+ book.title = "Updated Book Title"
313
+ book.author = "Bob Barker"
314
+
315
+ # MySQL version
316
+ Book.import [book], on_duplicate_key_update: [:title]
317
+
318
+ # PostgreSQL version
319
+ Book.import [book], on_duplicate_key_update: {conflict_target: [:id], columns: [:title]}
320
+
321
+ # PostgreSQL shorthand version (conflict target must be primary key)
322
+ Book.import [book], on_duplicate_key_update: [:title]
323
+
324
+ book.reload.title # => "Updated Book Title" (changed)
325
+ book.reload.author # => "George Orwell" (stayed the same)
326
+ ```
327
+
328
+ Using the value from another column
329
+
330
+ ```ruby
331
+ book = Book.create! title: "Book1", author: "George Orwell"
332
+ book.title = "Updated Book Title"
333
+
334
+ # MySQL version
335
+ Book.import [book], on_duplicate_key_update: {author: :title}
336
+
337
+ # PostgreSQL version (no shorthand version)
338
+ Book.import [book], on_duplicate_key_update: {
339
+ conflict_target: [:id], columns: {author: :title}
340
+ }
341
+
342
+ book.reload.title # => "Book1" (stayed the same)
343
+ book.reload.author # => "Updated Book Title" (changed)
344
+ ```
345
+
346
+ Using Custom SQL
347
+
348
+ ```ruby
349
+ book = Book.create! title: "Book1", author: "George Orwell"
350
+ book.author = "Bob Barker"
351
+
352
+ # MySQL version
353
+ Book.import [book], on_duplicate_key_update: "author = values(author)"
354
+
355
+ # PostgreSQL version
356
+ Book.import [book], on_duplicate_key_update: {
357
+ conflict_target: [:id], columns: "author = excluded.author"
358
+ }
359
+
360
+ # PostgreSQL shorthand version (conflict target must be primary key)
361
+ Book.import [book], on_duplicate_key_update: "author = excluded.author"
362
+
363
+ book.reload.title # => "Book1" (stayed the same)
364
+ book.reload.author # => "Bob Barker" (changed)
365
+ ```
366
+
367
+ PostgreSQL Using constraints
368
+
369
+ ```ruby
370
+ book = Book.create! title: "Book1", author: "George Orwell", edition: 3, published_at: nil
371
+ book.published_at = Time.now
372
+
373
+ # in migration
374
+ execute <<-SQL
375
+ ALTER TABLE books
376
+ ADD CONSTRAINT for_upsert UNIQUE (title, author, edition);
377
+ SQL
378
+
379
+ # PostgreSQL version
380
+ Book.import [book], on_duplicate_key_update: {constraint_name: :for_upsert, columns: [:published_at]}
381
+
382
+
383
+ book.reload.title # => "Book1" (stayed the same)
384
+ book.reload.author # => "George Orwell" (stayed the same)
385
+ book.reload.edition # => 3 (stayed the same)
386
+ book.reload.published_at # => 2017-10-09 (changed)
387
+ ```
388
+
389
+ ```ruby
390
+ Book.import books, validate_uniqueness: true
391
+ ```
392
+
393
+ ### Return Info
394
+
395
+ The `import` method returns a `Result` object that responds to `failed_instances` and `num_inserts`. Additionally, for users of Postgres, there will be two arrays `ids` and `results` that can be accessed`.
396
+
397
+ ```ruby
398
+ articles = [
399
+ Article.new(author_id: 1, title: 'First Article', content: 'This is the first article'),
400
+ Article.new(author_id: 2, title: 'Second Article', content: ''),
401
+ Article.new(author_id: 3, content: '')
402
+ ]
403
+
404
+ demo = Article.import(articles, returning: :title) # => #<struct ActiveRecord::Import::Result
405
+
406
+ demo.failed_instances
407
+ => [#<Article id: 3, author_id: 3, title: nil, content: "", created_at: nil, updated_at: nil>]
408
+
409
+ demo.num_inserts
410
+ => 1,
411
+
412
+ demo.ids
413
+ => ["1", "2"] # for Postgres
414
+ => [] # for other DBs
415
+
416
+ demo.results
417
+ => ["First Article", "Second Article"] # for Postgres
418
+ => [] # for other DBs
419
+ ```
420
+
421
+ ### Counter Cache
422
+
423
+ When running `import`, `activerecord-import` does not automatically update counter cache columns. To update these columns, you will need to do one of the following:
424
+
425
+ * Provide values to the column as an argument on your object that is passed in.
426
+ * Manually update the column after the record has been imported.
427
+
428
+ ### ActiveRecord Timestamps
429
+
430
+ If you're familiar with ActiveRecord you're probably familiar with its timestamp columns: created_at, created_on, updated_at, updated_on, etc. When importing data the timestamp fields will continue to work as expected and each timestamp column will be set.
431
+
432
+ Should you wish to specify those columns, you may use the option `timestamps: false`.
433
+
434
+ However, it is also possible to set just `:created_at` in specific records. In this case despite using `timestamps: true`, `:created_at` will be updated only in records where that field is `nil`. Same rule applies for record associations when enabling the option `recursive: true`.
435
+
436
+ If you are using custom time zones, these will be respected when performing imports as well as long as `ActiveRecord::Base.default_timezone` is set, which for practically all Rails apps it is
437
+
438
+ ### Callbacks
439
+
440
+ ActiveRecord callbacks related to [creating](http://guides.rubyonrails.org/active_record_callbacks.html#creating-an-object), [updating](http://guides.rubyonrails.org/active_record_callbacks.html#updating-an-object), or [destroying](http://guides.rubyonrails.org/active_record_callbacks.html#destroying-an-object) records (other than `before_validation` and `after_validation`) will NOT be called when calling the import method. This is because it is mass importing rows of data and doesn't necessarily have access to in-memory ActiveRecord objects.
441
+
442
+ If you do have a collection of in-memory ActiveRecord objects you can do something like this:
443
+
444
+ ```ruby
445
+ books.each do |book|
446
+ book.run_callbacks(:save) { false }
447
+ book.run_callbacks(:create) { false }
448
+ end
449
+ Book.import(books)
450
+ ```
451
+
452
+ This will run before_create and before_save callbacks on each item. The `false` argument is needed to prevent after_save being run, which wouldn't make sense prior to bulk import. Something to note in this example is that the before_create and before_save callbacks will run before the validation callbacks.
453
+
454
+ If that is an issue, another possible approach is to loop through your models first to do validations and then only run callbacks on and import the valid models.
455
+
456
+ ```ruby
457
+ valid_books = []
458
+ invalid_books = []
459
+
460
+ books.each do |book|
461
+ if book.valid?
462
+ valid_books << book
463
+ else
464
+ invalid_books << book
465
+ end
466
+ end
467
+
468
+ valid_books.each do |book|
469
+ book.run_callbacks(:save) { false }
470
+ book.run_callbacks(:create) { false }
471
+ end
472
+
473
+ Book.import valid_books, validate: false
474
+ ```
475
+
476
+ ### Supported Adapters
477
+
478
+ The following database adapters are currently supported:
479
+
480
+ * MySQL - supports core import functionality plus on duplicate key update support (included in activerecord-import 0.1.0 and higher)
481
+ * MySQL2 - supports core import functionality plus on duplicate key update support (included in activerecord-import 0.2.0 and higher)
482
+ * PostgreSQL - supports core import functionality (included in activerecord-import 0.1.0 and higher)
483
+ * SQLite3 - supports core import functionality (included in activerecord-import 0.1.0 and higher)
484
+ * Oracle - supports core import functionality through DML trigger (available as an external gem: [activerecord-import-oracle_enhanced](https://github.com/keeguon/activerecord-import-oracle_enhanced)
485
+ * SQL Server - supports core import functionality (available as an external gem: [activerecord-import-sqlserver](https://github.com/keeguon/activerecord-import-sqlserver)
486
+
487
+ If your adapter isn't listed here, please consider creating an external gem as described in the README to provide support. If you do, feel free to update this wiki to include a link to the new adapter's repository!
488
+
489
+ To test which features are supported by your adapter, use the following methods on a model class:
490
+ * `supports_import?(*args)`
491
+ * `supports_on_duplicate_key_update?`
492
+ * `supports_setting_primary_key_of_imported_objects?`
493
+
494
+ ### Additional Adapters
47
495
 
48
- ## Additional Adapters
49
496
  Additional adapters can be provided by gems external to activerecord-import by providing an adapter that matches the naming convention setup by activerecord-import (and subsequently activerecord) for dynamically loading adapters. This involves also providing a folder on the load path that follows the activerecord-import naming convention to allow activerecord-import to dynamically load the file.
50
497
 
51
498
  When `ActiveRecord::Import.require_adapter("fake_name")` is called the require will be:
52
499
 
53
500
  ```ruby
54
- require 'activerecord-import/active_record/adapters/fake_name_adapter'
501
+ require 'activerecord-import/active_record/adapters/fake_name_adapter'
502
+ ```
503
+
504
+ This allows an external gem to dynamically add an adapter without the need to add any file/code to the core activerecord-import gem.
505
+
506
+ ### Requiring
507
+
508
+ Note: These instructions will only work if you are using version 0.2.0 or higher.
509
+
510
+ #### Autoloading via Bundler
511
+
512
+ If you are using Rails or otherwise autoload your dependencies via Bundler, all you need to do add the gem to your `Gemfile` like so:
513
+
514
+ ```ruby
515
+ gem 'activerecord-import'
516
+ ```
517
+
518
+ #### Manually Loading
519
+
520
+ You may want to manually load activerecord-import for one reason or another. First, add the `require: false` argument like so:
521
+
522
+ ```ruby
523
+ gem 'activerecord-import', require: false
55
524
  ```
56
525
 
57
- This allows an external gem to dyanmically add an adapter without the need to add any file/code to the core activerecord-import gem.
526
+ This will allow you to load up activerecord-import in the file or files where you are using it and only load the parts you need.
527
+ If you are doing this within Rails and ActiveRecord has established a database connection (such as within a controller), you will need to do extra initialization work:
528
+
529
+ ```ruby
530
+ require 'activerecord-import/base'
531
+ # load the appropriate database adapter (postgresql, mysql2, sqlite3, etc)
532
+ require 'activerecord-import/active_record/adapters/postgresql_adapter'
533
+ ```
534
+
535
+ If your gem dependencies aren’t autoloaded, and your script will be establishing a database connection, then simply require activerecord-import after ActiveRecord has been loaded, i.e.:
536
+
537
+ ```ruby
538
+ require 'active_record'
539
+ require 'activerecord-import'
540
+ ```
58
541
 
59
542
  ### Load Path Setup
60
543
  To understand how rubygems loads code you can reference the following:
61
544
 
62
- http://guides.rubygems.org/patterns/#loading_code
545
+ http://guides.rubygems.org/patterns/#loading-code
63
546
 
64
547
  And an example of how active_record dynamically load adapters:
548
+
65
549
  https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/connection_specification.rb
66
550
 
67
551
  In summary, when a gem is loaded rubygems adds the `lib` folder of the gem to the global load path `$LOAD_PATH` so that all `require` lookups will not propagate through all of the folders on the load path. When a `require` is issued each folder on the `$LOAD_PATH` is checked for the file and/or folder referenced. This allows a gem (like activerecord-import) to define push the activerecord-import folder (or namespace) on the `$LOAD_PATH` and any adapters provided by activerecord-import will be found by rubygems when the require is issued.
@@ -72,34 +556,81 @@ If `fake_name` adapter is needed by a gem (potentially called `activerecord-impo
72
556
  activerecord-import-fake_name/
73
557
  |-- activerecord-import-fake_name.gemspec
74
558
  |-- lib
559
+ | |-- activerecord-import-fake_name.rb
75
560
  | |-- activerecord-import-fake_name
76
561
  | | |-- version.rb
77
562
  | |-- activerecord-import
78
563
  | | |-- active_record
79
564
  | | | |-- adapters
80
565
  | | | |-- fake_name_adapter.rb
81
- |--activerecord-import-fake_name.rb
82
566
  ```
83
567
 
84
568
  When rubygems pushes the `lib` folder onto the load path a `require` will now find `activerecord-import/active_record/adapters/fake_name_adapter` as it runs through the lookup process for a ruby file under that path in `$LOAD_PATH`
85
569
 
570
+
571
+ ### Conflicts With Other Gems
572
+
573
+ Activerecord-Import adds the `.import` method onto `ActiveRecord::Base`. There are other gems, such as `elasticsearch-rails`, that do the same thing. In conflicts such as this, there is an aliased method named `.bulk_import` that can be used interchangeably.
574
+
575
+ If you are using the `apartment` gem, there is a weird triple interaction between that gem, `activerecord-import`, and `activerecord` involving caching of the `sequence_name` of a model. This can be worked around by explcitly setting this value within the model. For example:
576
+
577
+ ```ruby
578
+ class Post < ActiveRecord::Base
579
+ self.sequence_name = "posts_seq"
580
+ end
581
+ ```
582
+
583
+ Another way to work around the issue is to call `.reset_sequence_name` on the model. For example:
584
+
585
+ ```ruby
586
+ schemas.all.each do |schema|
587
+ Apartment::Tenant.switch! schema.name
588
+ ActiveRecord::Base.transaction do
589
+ Post.reset_sequence_name
590
+
591
+ Post.import posts
592
+ end
593
+ end
594
+ ```
595
+
596
+ See https://github.com/zdennis/activerecord-import/issues/233 for further discussion.
597
+
598
+ ### More Information
599
+
600
+ For more information on Activerecord-Import please see its wiki: https://github.com/zdennis/activerecord-import/wiki
601
+
602
+ To document new information, please add to the README instead of the wiki. See https://github.com/zdennis/activerecord-import/issues/397 for discussion.
603
+
604
+ ### Contributing
605
+
606
+ #### Running Tests
607
+
608
+ The first thing you need to do is set up your database(s):
609
+
610
+ * copy `test/database.yml.sample` to `test/database.yml`
611
+ * modify `test/database.yml` for your database settings
612
+ * create databases as needed
613
+
614
+ After that, you can run the tests. They run against multiple tests and ActiveRecord versions.
615
+
616
+ This is one example of how to run the tests:
617
+
618
+ ```ruby
619
+ rm Gemfile.lock
620
+ AR_VERSION=4.2 bundle install
621
+ AR_VERSION=4.2 bundle exec rake test:postgresql test:sqlite3 test:mysql2
622
+ ```
623
+
624
+ Once you have pushed up your changes, you can find your CI results [here](https://travis-ci.org/zdennis/activerecord-import/).
625
+
626
+ ## Issue Triage [![Open Source Helpers](https://www.codetriage.com/zdennis/activerecord-import/badges/users.svg)](https://www.codetriage.com/zdennis/activerecord-import)
627
+
628
+ You can triage issues which may include reproducing bug reports or asking for vital information, such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to activerecord-import on CodeTriage](https://www.codetriage.com/zdennis/activerecord-import).
629
+
86
630
  # License
87
631
 
88
- This is licensed under the ruby license.
632
+ This is licensed under the MIT license.
89
633
 
90
634
  # Author
91
635
 
92
636
  Zach Dennis (zach.dennis@gmail.com)
93
-
94
- # Contributors
95
-
96
- * Jordan Owens (@jkowens)
97
- * Erik Michaels-Ober (@sferik)
98
- * Blythe Dunham
99
- * Gabe da Silveira
100
- * Henry Work
101
- * James Herdman
102
- * Marcus Crafter
103
- * Thibaud Guillaume-Gentil
104
- * Mark Van Holstyn
105
- * Victor Costan