Module: Sequel::Plugins::FromCsv::ClassMethods
- Defined in:
- lib/sequel/plugins/from_csv.rb
Instance Method Summary collapse
-
#seed_from_csv(csv_path, delete: false) ⇒ Object
Synchronizes a table’s data with a CSV file.
Instance Method Details
#seed_from_csv(csv_path, delete: false) ⇒ Object
Synchronizes a table’s data with a CSV file
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 |
# File 'lib/sequel/plugins/from_csv.rb', line 10 def seed_from_csv csv_path, delete: false # Read the source CSV file data = CSV.table csv_path # Ensure the ID column exists unless data.first[:id] raise "CSV file #{csv_path} must contain an id column" end self.db.transaction do # UPSERT data.each do |row| row = row.to_h # Convert CSV::Row to Hash self.dataset.insert_conflict(target: :id, update: row).insert row end # DELETE old rows if delete self.exclude("id IN ?", data.map{|row| row[:id]}).delete end # Update the table's sequence self.db.run <<~SQL SELECT setval(pg_get_serial_sequence('#{self.simple_table}', 'id'), coalesce(max(id), 1), true) FROM #{self.simple_table} SQL end end |