-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload_csv_pg.rb
43 lines (36 loc) · 1.09 KB
/
load_csv_pg.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
require 'sequel'
require 'CSV'
require 'trollop'
opts = Trollop.options do
opt :csv, "csv file", type: :string, required: true
opt :db, "database", type: :string, required: true
opt :host, "database", default: 'localhost'
opt :user, "user", type: :string, required: true
opt :table, "table", type: :string, required: true
opt :replace, "replace existing table"
opt :append, "append data to existing table"
end
csv = CSV.table(opts[:csv])
db = Sequel.postgres(host: opts[:host],
user: opts[:user],
password: opts[:password],
database: opts[:db])
def create_table(db, table, headers, opts)
table = table.to_sym
# TODO: verify matching columns on extant table
unless opts[:append]
if opts[:replace]
db.drop_table?(table)
end
db.create_table(table) do
headers.each do |col|
# TODO: infer column type
String col
end
end
end
db[table]
end
tbl = create_table(db, opts[:table], csv.headers, opts)
tbl.import(csv.headers,
csv.entries.map { |e| e.to_hash.values })