activerecord-import 0.10.0 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. checksums.yaml +5 -5
  2. data/.gitignore +1 -0
  3. data/.rubocop.yml +49 -0
  4. data/.rubocop_todo.yml +36 -0
  5. data/.travis.yml +64 -8
  6. data/CHANGELOG.md +475 -0
  7. data/Gemfile +32 -15
  8. data/LICENSE +21 -56
  9. data/README.markdown +564 -35
  10. data/Rakefile +20 -3
  11. data/activerecord-import.gemspec +7 -7
  12. data/benchmarks/README +2 -2
  13. data/benchmarks/benchmark.rb +68 -64
  14. data/benchmarks/lib/base.rb +138 -137
  15. data/benchmarks/lib/cli_parser.rb +107 -103
  16. data/benchmarks/lib/{mysql_benchmark.rb → mysql2_benchmark.rb} +19 -22
  17. data/benchmarks/lib/output_to_csv.rb +5 -4
  18. data/benchmarks/lib/output_to_html.rb +8 -13
  19. data/benchmarks/models/test_innodb.rb +1 -1
  20. data/benchmarks/models/test_memory.rb +1 -1
  21. data/benchmarks/models/test_myisam.rb +1 -1
  22. data/benchmarks/schema/mysql2_schema.rb +16 -0
  23. data/gemfiles/3.2.gemfile +2 -4
  24. data/gemfiles/4.0.gemfile +2 -4
  25. data/gemfiles/4.1.gemfile +2 -4
  26. data/gemfiles/4.2.gemfile +2 -4
  27. data/gemfiles/5.0.gemfile +2 -0
  28. data/gemfiles/5.1.gemfile +2 -0
  29. data/gemfiles/5.2.gemfile +2 -0
  30. data/gemfiles/6.0.gemfile +2 -0
  31. data/gemfiles/6.1.gemfile +1 -0
  32. data/lib/activerecord-import/active_record/adapters/jdbcsqlite3_adapter.rb +6 -0
  33. data/lib/activerecord-import/active_record/adapters/sqlite3_adapter.rb +0 -1
  34. data/lib/activerecord-import/adapters/abstract_adapter.rb +23 -17
  35. data/lib/activerecord-import/adapters/mysql_adapter.rb +52 -25
  36. data/lib/activerecord-import/adapters/postgresql_adapter.rb +187 -10
  37. data/lib/activerecord-import/adapters/sqlite3_adapter.rb +148 -17
  38. data/lib/activerecord-import/base.rb +15 -9
  39. data/lib/activerecord-import/import.rb +740 -191
  40. data/lib/activerecord-import/synchronize.rb +21 -21
  41. data/lib/activerecord-import/value_sets_parser.rb +33 -8
  42. data/lib/activerecord-import/version.rb +1 -1
  43. data/lib/activerecord-import.rb +4 -15
  44. data/test/adapters/jdbcsqlite3.rb +1 -0
  45. data/test/adapters/makara_postgis.rb +1 -0
  46. data/test/adapters/mysql2_makara.rb +1 -0
  47. data/test/adapters/mysql2spatial.rb +1 -1
  48. data/test/adapters/postgis.rb +1 -1
  49. data/test/adapters/postgresql.rb +1 -1
  50. data/test/adapters/postgresql_makara.rb +1 -0
  51. data/test/adapters/spatialite.rb +1 -1
  52. data/test/adapters/sqlite3.rb +1 -1
  53. data/test/database.yml.sample +13 -18
  54. data/test/import_test.rb +608 -89
  55. data/test/jdbcmysql/import_test.rb +2 -3
  56. data/test/jdbcpostgresql/import_test.rb +0 -2
  57. data/test/jdbcsqlite3/import_test.rb +4 -0
  58. data/test/makara_postgis/import_test.rb +8 -0
  59. data/test/models/account.rb +3 -0
  60. data/test/models/alarm.rb +2 -0
  61. data/test/models/animal.rb +6 -0
  62. data/test/models/bike_maker.rb +7 -0
  63. data/test/models/book.rb +7 -6
  64. data/test/models/car.rb +3 -0
  65. data/test/models/chapter.rb +2 -2
  66. data/test/models/dictionary.rb +4 -0
  67. data/test/models/discount.rb +3 -0
  68. data/test/models/end_note.rb +2 -2
  69. data/test/models/promotion.rb +3 -0
  70. data/test/models/question.rb +3 -0
  71. data/test/models/rule.rb +3 -0
  72. data/test/models/tag.rb +4 -0
  73. data/test/models/topic.rb +17 -3
  74. data/test/models/user.rb +3 -0
  75. data/test/models/user_token.rb +4 -0
  76. data/test/models/vendor.rb +7 -0
  77. data/test/models/widget.rb +19 -2
  78. data/test/mysql2/import_test.rb +2 -3
  79. data/test/{em_mysql2 → mysql2_makara}/import_test.rb +1 -1
  80. data/test/mysqlspatial2/import_test.rb +2 -2
  81. data/test/postgis/import_test.rb +5 -1
  82. data/test/schema/generic_schema.rb +159 -85
  83. data/test/schema/jdbcpostgresql_schema.rb +1 -0
  84. data/test/schema/mysql2_schema.rb +19 -0
  85. data/test/schema/postgis_schema.rb +1 -0
  86. data/test/schema/postgresql_schema.rb +61 -0
  87. data/test/schema/sqlite3_schema.rb +13 -0
  88. data/test/sqlite3/import_test.rb +2 -50
  89. data/test/support/active_support/test_case_extensions.rb +21 -13
  90. data/test/support/{mysql/assertions.rb → assertions.rb} +20 -2
  91. data/test/support/factories.rb +39 -14
  92. data/test/support/generate.rb +10 -10
  93. data/test/support/mysql/import_examples.rb +49 -98
  94. data/test/support/postgresql/import_examples.rb +535 -57
  95. data/test/support/shared_examples/on_duplicate_key_ignore.rb +43 -0
  96. data/test/support/shared_examples/on_duplicate_key_update.rb +378 -0
  97. data/test/support/shared_examples/recursive_import.rb +225 -0
  98. data/test/support/sqlite3/import_examples.rb +231 -0
  99. data/test/synchronize_test.rb +10 -2
  100. data/test/test_helper.rb +36 -8
  101. data/test/travis/database.yml +26 -17
  102. data/test/value_sets_bytes_parser_test.rb +25 -17
  103. data/test/value_sets_records_parser_test.rb +6 -6
  104. metadata +86 -42
  105. data/benchmarks/boot.rb +0 -18
  106. data/benchmarks/schema/mysql_schema.rb +0 -16
  107. data/gemfiles/3.1.gemfile +0 -4
  108. data/lib/activerecord-import/active_record/adapters/em_mysql2_adapter.rb +0 -8
  109. data/lib/activerecord-import/active_record/adapters/mysql_adapter.rb +0 -6
  110. data/lib/activerecord-import/em_mysql2.rb +0 -7
  111. data/lib/activerecord-import/mysql.rb +0 -7
  112. data/test/adapters/em_mysql2.rb +0 -1
  113. data/test/adapters/mysql.rb +0 -1
  114. data/test/adapters/mysqlspatial.rb +0 -1
  115. data/test/mysql/import_test.rb +0 -6
  116. data/test/mysqlspatial/import_test.rb +0 -6
  117. data/test/schema/mysql_schema.rb +0 -18
  118. data/test/travis/build.sh +0 -30
data/README.markdown CHANGED
@@ -1,62 +1,542 @@
1
- # 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
7
7
  explains it best. Say you had a schema like this:
8
-
9
- Publishers have Books
10
- Books have Reviews
11
-
8
+
9
+ - Publishers have Books
10
+ - Books have Reviews
11
+
12
12
  and you wanted to bulk insert 100 new publishers with 10K books and 3 reviews per book. This library will follow the associations
13
13
  down and generate only 3 SQL insert statements - one for the publishers, one for the books, and one for the reviews.
14
-
14
+
15
15
  In contrast, the standard ActiveRecord save would generate
16
16
  100 insert statements for the publishers, then it would visit each publisher and save all the books:
17
17
  100 * 10,000 = 1,000,000 SQL insert statements
18
18
  and then the reviews:
19
19
  100 * 10,000 * 3 = 3M SQL insert statements,
20
-
20
+
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 4.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:
66
+
67
+ ```ruby
68
+ 10.times do |i|
69
+ Book.create! name: "book #{i}"
70
+ end
71
+ ```
72
+
73
+ This would end up making 10 SQL calls. YUCK! With `activerecord-import`, you can instead do this:
74
+
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
+ ```
82
+
83
+ and only have 1 SQL call. Much better!
84
+
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'] ]
92
+
93
+ # Importing without model validations
94
+ Book.import columns, values, validate: false
95
+
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'}]
109
+
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
+ ```
146
+
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.
148
+
149
+ See https://github.com/zdennis/activerecord-import/issues/507 for discussion.
150
+
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
+ #### Recursive
235
+
236
+ NOTE: This only works with PostgreSQL and ActiveRecord objects. This won't work with
237
+ hashes or arrays as recursive inputs.
238
+
239
+ Assume that Books <code>has_many</code> Reviews.
240
+
241
+ ```ruby
242
+ books = []
243
+ 10.times do |i|
244
+ book = Book.new(name: "book #{i}")
245
+ book.reviews.build(title: "Excellent")
246
+ books << book
247
+ end
248
+ Book.import books, recursive: true
249
+ ```
250
+
251
+ ### Options
252
+
253
+ Key | Options | Default | Description
254
+ ------------------------- | --------------------- | ------------------ | -----------
255
+ :validate | `true`/`false` | `true` | Whether or not to run `ActiveRecord` validations (uniqueness skipped). This option will always be true when using `import!`.
256
+ :validate_uniqueness | `true`/`false` | `false` | Whether or not to run uniqueness validations, has potential pitfalls, use with caution (requires `>= v0.27.0`).
257
+ :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.
258
+ :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]`
259
+ :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.
260
+ :ignore | `true`/`false` | `false` | Alias for :on_duplicate_key_ignore.
261
+ :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.
262
+ :synchronize | `Array` | N/A | An array of ActiveRecord instances. This synchronizes existing instances in memory with updates from the import.
263
+ :timestamps | `true`/`false` | `true` | Enables/disables timestamps on imported records.
264
+ :recursive | `true`/`false` | `false` | Imports has_many/has_one associations (PostgreSQL only).
265
+ :batch_size | `Integer` | total # of records | Max number of records to insert per import
266
+ :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.
267
+ :all_or_none | `true`/`false` | `false` | Will not import any records if there is a record with validation errors.
268
+
269
+ #### Duplicate Key Ignore
270
+
271
+ [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.
272
+
273
+ 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.
274
+
275
+ ```ruby
276
+ book = Book.create! title: "Book1", author: "George Orwell"
277
+ book.title = "Updated Book Title"
278
+ book.author = "Bob Barker"
279
+
280
+ Book.import [book], on_duplicate_key_ignore: true
281
+
282
+ book.reload.title # => "Book1" (stayed the same)
283
+ book.reload.author # => "George Orwell" (stayed the same)
284
+ ```
285
+
286
+ 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).
287
+
288
+ #### Duplicate Key Update
289
+
290
+ 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.
291
+
292
+ 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.
293
+
294
+ This will use MySQL's `ON DUPLICATE KEY UPDATE` or Postgres/SQLite `ON CONFLICT DO UPDATE` to do upsert.
295
+
296
+ Basic Update
297
+
298
+ ```ruby
299
+ book = Book.create! title: "Book1", author: "George Orwell"
300
+ book.title = "Updated Book Title"
301
+ book.author = "Bob Barker"
302
+
303
+ # MySQL version
304
+ Book.import [book], on_duplicate_key_update: [:title]
305
+
306
+ # PostgreSQL version
307
+ Book.import [book], on_duplicate_key_update: {conflict_target: [:id], columns: [:title]}
308
+
309
+ # PostgreSQL shorthand version (conflict target must be primary key)
310
+ Book.import [book], on_duplicate_key_update: [:title]
311
+
312
+ book.reload.title # => "Updated Book Title" (changed)
313
+ book.reload.author # => "George Orwell" (stayed the same)
314
+ ```
315
+
316
+ Using the value from another column
317
+
318
+ ```ruby
319
+ book = Book.create! title: "Book1", author: "George Orwell"
320
+ book.title = "Updated Book Title"
321
+
322
+ # MySQL version
323
+ Book.import [book], on_duplicate_key_update: {author: :title}
324
+
325
+ # PostgreSQL version (no shorthand version)
326
+ Book.import [book], on_duplicate_key_update: {
327
+ conflict_target: [:id], columns: {author: :title}
328
+ }
329
+
330
+ book.reload.title # => "Book1" (stayed the same)
331
+ book.reload.author # => "Updated Book Title" (changed)
332
+ ```
333
+
334
+ Using Custom SQL
335
+
336
+ ```ruby
337
+ book = Book.create! title: "Book1", author: "George Orwell"
338
+ book.author = "Bob Barker"
339
+
340
+ # MySQL version
341
+ Book.import [book], on_duplicate_key_update: "author = values(author)"
342
+
343
+ # PostgreSQL version
344
+ Book.import [book], on_duplicate_key_update: {
345
+ conflict_target: [:id], columns: "author = excluded.author"
346
+ }
347
+
348
+ # PostgreSQL shorthand version (conflict target must be primary key)
349
+ Book.import [book], on_duplicate_key_update: "author = excluded.author"
350
+
351
+ book.reload.title # => "Book1" (stayed the same)
352
+ book.reload.author # => "Bob Barker" (changed)
353
+ ```
354
+
355
+ PostgreSQL Using constraints
356
+
357
+ ```ruby
358
+ book = Book.create! title: "Book1", author: "George Orwell", edition: 3, published_at: nil
359
+ book.published_at = Time.now
360
+
361
+ # in migration
362
+ execute <<-SQL
363
+ ALTER TABLE books
364
+ ADD CONSTRAINT for_upsert UNIQUE (title, author, edition);
365
+ SQL
366
+
367
+ # PostgreSQL version
368
+ Book.import [book], on_duplicate_key_update: {constraint_name: :for_upsert, columns: [:published_at]}
369
+
370
+
371
+ book.reload.title # => "Book1" (stayed the same)
372
+ book.reload.author # => "George Orwell" (stayed the same)
373
+ book.reload.edition # => 3 (stayed the same)
374
+ book.reload.published_at # => 2017-10-09 (changed)
375
+ ```
376
+
377
+ ```ruby
378
+ Book.import books, validate_uniqueness: true
379
+ ```
380
+
381
+ ### Return Info
382
+
383
+ 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`.
384
+
385
+ ```ruby
386
+ articles = [
387
+ Article.new(author_id: 1, title: 'First Article', content: 'This is the first article'),
388
+ Article.new(author_id: 2, title: 'Second Article', content: ''),
389
+ Article.new(author_id: 3, content: '')
390
+ ]
391
+
392
+ demo = Article.import(articles, returning: :title) # => #<struct ActiveRecord::Import::Result
393
+
394
+ demo.failed_instances
395
+ => [#<Article id: 3, author_id: 3, title: nil, content: "", created_at: nil, updated_at: nil>]
396
+
397
+ demo.num_inserts
398
+ => 1,
399
+
400
+ demo.ids
401
+ => ["1", "2"] # for Postgres
402
+ => [] # for other DBs
403
+
404
+ demo.results
405
+ => ["First Article", "Second Article"] # for Postgres
406
+ => [] # for other DBs
407
+ ```
408
+
409
+ ### Counter Cache
410
+
411
+ 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:
412
+
413
+ * Provide values to the column as an argument on your object that is passed in.
414
+ * Manually update the column after the record has been imported.
415
+
416
+ ### ActiveRecord Timestamps
417
+
418
+ 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.
419
+
420
+ Should you wish to specify those columns, you may use the option `timestamps: false`.
421
+
422
+ 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`.
423
+
424
+ 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
425
+
426
+ ### Callbacks
427
+
428
+ 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.
429
+
430
+ If you do have a collection of in-memory ActiveRecord objects you can do something like this:
431
+
432
+ ```ruby
433
+ books.each do |book|
434
+ book.run_callbacks(:save) { false }
435
+ book.run_callbacks(:create) { false }
436
+ end
437
+ Book.import(books)
438
+ ```
439
+
440
+ 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.
441
+
442
+ 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.
443
+
444
+ ```ruby
445
+ valid_books = []
446
+ invalid_books = []
447
+
448
+ books.each do |book|
449
+ if book.valid?
450
+ valid_books << book
451
+ else
452
+ invalid_books << book
453
+ end
454
+ end
25
455
 
26
- Use activerecord-import 0.4.0 or higher.
456
+ valid_books.each do |book|
457
+ book.run_callbacks(:save) { false }
458
+ book.run_callbacks(:create) { false }
459
+ end
27
460
 
28
- ### Rails 3.1.x up to, but not including 4.0
461
+ Book.import valid_books, validate: false
462
+ ```
463
+
464
+ ### Supported Adapters
29
465
 
30
- Use the latest in the activerecord-import 0.3.x series.
466
+ The following database adapters are currently supported:
31
467
 
32
- ### Rails 3.0.x up to, but not including 3.1
468
+ * MySQL - supports core import functionality plus on duplicate key update support (included in activerecord-import 0.1.0 and higher)
469
+ * MySQL2 - supports core import functionality plus on duplicate key update support (included in activerecord-import 0.2.0 and higher)
470
+ * PostgreSQL - supports core import functionality (included in activerecord-import 0.1.0 and higher)
471
+ * SQLite3 - supports core import functionality (included in activerecord-import 0.1.0 and higher)
472
+ * 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)
473
+ * SQL Server - supports core import functionality (available as an external gem: [activerecord-import-sqlserver](https://github.com/keeguon/activerecord-import-sqlserver)
33
474
 
34
- 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.
475
+ 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!
35
476
 
36
- ### For More Information
477
+ To test which features are supported by your adapter, use the following methods on a model class:
478
+ * `supports_import?(*args)`
479
+ * `supports_on_duplicate_key_update?`
480
+ * `supports_setting_primary_key_of_imported_objects?`
37
481
 
38
- For more information on activerecord-import please see its wiki: https://github.com/zdennis/activerecord-import/wiki
482
+ ### Additional Adapters
39
483
 
40
- ## Additional Adapters
41
484
  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.
42
485
 
43
486
  When `ActiveRecord::Import.require_adapter("fake_name")` is called the require will be:
44
487
 
45
488
  ```ruby
46
- require 'activerecord-import/active_record/adapters/fake_name_adapter'
489
+ require 'activerecord-import/active_record/adapters/fake_name_adapter'
490
+ ```
491
+
492
+ This allows an external gem to dynamically add an adapter without the need to add any file/code to the core activerecord-import gem.
493
+
494
+ ### Requiring
495
+
496
+ Note: These instructions will only work if you are using version 0.2.0 or higher.
497
+
498
+ #### Autoloading via Bundler
499
+
500
+ 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:
501
+
502
+ ```ruby
503
+ gem 'activerecord-import'
47
504
  ```
48
505
 
49
- This allows an external gem to dyanmically add an adapter without the need to add any file/code to the core activerecord-import gem.
506
+ #### Manually Loading
507
+
508
+ You may want to manually load activerecord-import for one reason or another. First, add the `require: false` argument like so:
509
+
510
+ ```ruby
511
+ gem 'activerecord-import', require: false
512
+ ```
513
+
514
+ 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.
515
+ 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:
516
+
517
+ ```ruby
518
+ require 'activerecord-import/base'
519
+ # load the appropriate database adapter (postgresql, mysql2, sqlite3, etc)
520
+ require 'activerecord-import/active_record/adapters/postgresql_adapter'
521
+ ```
522
+
523
+ 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.:
524
+
525
+ ```ruby
526
+ require 'active_record'
527
+ require 'activerecord-import'
528
+ ```
50
529
 
51
530
  ### Load Path Setup
52
531
  To understand how rubygems loads code you can reference the following:
53
532
 
54
- http://guides.rubygems.org/patterns/#loading_code
533
+ http://guides.rubygems.org/patterns/#loading-code
55
534
 
56
535
  And an example of how active_record dynamically load adapters:
57
- https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/connection_specification.rb
58
536
 
59
- 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 propegate 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.
537
+ https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/connection_specification.rb
538
+
539
+ 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.
60
540
 
61
541
  If `fake_name` adapter is needed by a gem (potentially called `activerecord-import-fake_name`) then the folder structure should look as follows:
62
542
 
@@ -64,32 +544,81 @@ If `fake_name` adapter is needed by a gem (potentially called `activerecord-impo
64
544
  activerecord-import-fake_name/
65
545
  |-- activerecord-import-fake_name.gemspec
66
546
  |-- lib
547
+ | |-- activerecord-import-fake_name.rb
67
548
  | |-- activerecord-import-fake_name
68
549
  | | |-- version.rb
69
550
  | |-- activerecord-import
70
551
  | | |-- active_record
71
552
  | | | |-- adapters
72
553
  | | | |-- fake_name_adapter.rb
73
- |--activerecord-import-fake_name.rb
74
554
  ```
75
555
 
76
556
  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`
77
557
 
558
+
559
+ ### Conflicts With Other Gems
560
+
561
+ 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.
562
+
563
+ 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:
564
+
565
+ ```ruby
566
+ class Post < ActiveRecord::Base
567
+ self.sequence_name = "posts_seq"
568
+ end
569
+ ```
570
+
571
+ Another way to work around the issue is to call `.reset_sequence_name` on the model. For example:
572
+
573
+ ```ruby
574
+ schemas.all.each do |schema|
575
+ Apartment::Tenant.switch! schema.name
576
+ ActiveRecord::Base.transaction do
577
+ Post.reset_sequence_name
578
+
579
+ Post.import posts
580
+ end
581
+ end
582
+ ```
583
+
584
+ See https://github.com/zdennis/activerecord-import/issues/233 for further discussion.
585
+
586
+ ### More Information
587
+
588
+ For more information on Activerecord-Import please see its wiki: https://github.com/zdennis/activerecord-import/wiki
589
+
590
+ To document new information, please add to the README instead of the wiki. See https://github.com/zdennis/activerecord-import/issues/397 for discussion.
591
+
592
+ ### Contributing
593
+
594
+ #### Running Tests
595
+
596
+ The first thing you need to do is set up your database(s):
597
+
598
+ * copy `test/database.yml.sample` to `test/database.yml`
599
+ * modify `test/database.yml` for your database settings
600
+ * create databases as needed
601
+
602
+ After that, you can run the tests. They run against multiple tests and ActiveRecord versions.
603
+
604
+ This is one example of how to run the tests:
605
+
606
+ ```ruby
607
+ rm Gemfile.lock
608
+ AR_VERSION=4.2 bundle install
609
+ AR_VERSION=4.2 bundle exec rake test:postgresql test:sqlite3 test:mysql2
610
+ ```
611
+
612
+ Once you have pushed up your changes, you can find your CI results [here](https://travis-ci.org/zdennis/activerecord-import/).
613
+
614
+ ## Issue Triage [![Open Source Helpers](https://www.codetriage.com/zdennis/activerecord-import/badges/users.svg)](https://www.codetriage.com/zdennis/activerecord-import)
615
+
616
+ 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).
617
+
78
618
  # License
79
619
 
80
- This is licensed under the ruby license.
620
+ This is licensed under the MIT license.
81
621
 
82
622
  # Author
83
623
 
84
624
  Zach Dennis (zach.dennis@gmail.com)
85
-
86
- # Contributors
87
-
88
- * Blythe Dunham
89
- * Gabe da Silveira
90
- * Henry Work
91
- * James Herdman
92
- * Marcus Crafter
93
- * Thibaud Guillaume-Gentil
94
- * Mark Van Holstyn
95
- * Victor Costan