+# frozen_string_literal: true
+
+require "csv"
+require "pry"
+require "sqlite3"
+
+class CancellationsLoader
+ def initialize
+ end
+
+ def create_table
+ cancellations_sql = <<~EOS
+ CREATE TABLE cancellations (
+ source_time VARCHAR(5),
+ id CHAR(1),
+ next_trip INTEGER,
+ is_statusnet CHAR(1),
+ source VARCHAR(48),
+ message VARCHAR(140),
+ route VARCHAR(3),
+ destination VARCHAR(48),
+ affected_route VARCHAR(48),
+ is_tweet CHAR(1),
+ destination_time VARCHAR(5)
+ );
+ EOS
+
+ db.execute cancellations_sql
+ end
+
+ def load_file(base_path:, filename:)
+ print "Loading #{filename}..."
+ $stdout.flush
+ db.execute("BEGIN TRANSACTION;")
+
+ filepath = File.join(base_path, filename)
+
+ cols = %w(source_time id next_trip is_statusnet source message route destination affected_route is_tweet destination_time)
+ count = 0
+
+ CSV.foreach(filepath, headers: true, col_sep: ",") do |row|
+ count += 1
+ values = cols.map{|col| row[col.to_s]}
+ placeholders = (["?"] * values.count).join(",")
+
+ sql = "INSERT INTO cancellations (#{cols.join(",")}) VALUES (#{placeholders})"
+
+ db.execute(sql, values)
+
+ if (0 == count % 10_000)
+ db.execute("COMMIT;")
+ db.execute("BEGIN TRANSACTION;")
+ print "."
+ $stdout.flush
+ end
+ end
+
+ db.execute("COMMIT;")
+ puts " done."
+ end
+
+ private
+
+ def db
+ @db ||= SQLite3::Database.new("gtfs.db")
+ end
+end