Skip to content

Commit 784530b

Browse files
authored
Merge pull request #69 from dcluna/temp-table-copy
Temp table convenience method
2 parents 73ec5d3 + 8917452 commit 784530b

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

README.md

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# postgres-copy
1+
# postgres-copy
22

33
![Ruby](https://github.com/diogob/postgres-copy/workflows/Ruby/badge.svg)
44

@@ -207,6 +207,19 @@ This is useful for removing byte order marks when matching column headers.
207207
User.copy_from "/tmp/users_with_byte_order_mark.csv", :encoding => 'bom|utf-8'
208208
```
209209

210+
### Using PostgresCopy::WithTempTable.generate
211+
212+
Based on [nfedyashev](https://github.com/nfedyashev)'s [comment](https://github.com/diogob/postgres-copy/issues/51):
213+
214+
```ruby
215+
PostgresCopy::WithTempTable.generate do |t|
216+
columns.each do |column_name|
217+
t.string column_name.to_sym
218+
end
219+
end
220+
```
221+
222+
This auto-generates an id column, but the temp table creation is configurable.
210223

211224
### Using the CSV Responder
212225
If you want to make the result of a COPY command available to download this gem provides a CSV responder that, in conjunction with [inherited_resources](https://github.com/josevalim/inherited_resources), is a very powerfull tool. BTW, do not try to use the responder without inherited_resources.

lib/postgres-copy/with_temp_table.rb

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
module PostgresCopy
2+
module WithTempTable
3+
def self.generate(connection = ActiveRecord::Base.connection, base_klass:
4+
ActiveRecord::Base, temp_table_name: nil, create_table_opts: {id: :bigint})
5+
raise "You have to pass a table schema definition block!" unless block_given?
6+
table_name = temp_table_name || "temp_table_#{SecureRandom.hex}"
7+
8+
connection.create_table table_name, temporary: true, **create_table_opts do |t|
9+
yield t
10+
end
11+
12+
klass = Class.new(base_klass) do
13+
acts_as_copy_target
14+
self.table_name = table_name
15+
end
16+
end
17+
end
18+
end
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
2+
require 'postgres-copy/with_temp_table'
3+
4+
describe '.generate' do
5+
subject(:generate) {
6+
PostgresCopy::WithTempTable.generate do |t|
7+
t.string :data
8+
end
9+
}
10+
11+
it {
12+
generate.copy_from 'spec/fixtures/comma_with_header.csv'
13+
data = generate.all.first
14+
expect(data.id).to eq(1)
15+
expect(data.data).to eq('test data 1')
16+
}
17+
end

0 commit comments

Comments
 (0)