|
| 1 | +#!/usr/bin/env ruby |
| 2 | + |
| 3 | +require 'csv' |
| 4 | +require 'active_record' |
| 5 | +require 'thor' |
| 6 | +require 'tmpdir' |
| 7 | + |
| 8 | +class ShopifyCSV < Thor |
| 9 | + RESERVED_COLUMN_NAMES = %w[select type id] |
| 10 | + |
| 11 | + class Result < ActiveRecord::Base |
| 12 | + def self.comments |
| 13 | + distinct.pluck(:import_comment) |
| 14 | + end |
| 15 | + |
| 16 | + def self.with_comment(text) |
| 17 | + where("import_comment LIKE ?", "%#{text}%") |
| 18 | + end |
| 19 | + end |
| 20 | + |
| 21 | + desc "analyze CSV_PATH", "Analyze results file at path CSV_PATH" |
| 22 | + method_option :force_import, type: :boolean, default: false |
| 23 | + method_option :tmp_dir, type: :string, default: Dir.tmpdir |
| 24 | + def analyze(csv_path) |
| 25 | + csv_path = File.expand_path(csv_path) |
| 26 | + underscore = ->(string) { string.downcase.gsub(/[^a-z0-9]+/, "_").gsub(/(^_+|_+$)/, "") } |
| 27 | + csv = CSV.open(csv_path, liberal_parsing:true ) |
| 28 | + header_to_column = -> { RESERVED_COLUMN_NAMES.include?(_1.to_s) ? "#{_1}_1" : _1 } |
| 29 | + headers = csv.shift.map(&underscore).map(&header_to_column) |
| 30 | + basename = File.basename csv_path |
| 31 | + database = "#{options[:tmp_dir]}/shopify-toolkit-analyze-#{underscore[basename]}.sqlite3" |
| 32 | + should_import = options[:force_import] || !File.exist?(database) |
| 33 | + to_record = ->(row) { headers.zip(row).to_h.transform_keys(&header_to_column) } |
| 34 | + |
| 35 | + File.delete(database) if should_import && File.exist?(database) |
| 36 | + |
| 37 | + ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database:) |
| 38 | + |
| 39 | + if should_import |
| 40 | + puts "==> Importing #{csv_path}" |
| 41 | + puts "-- database: #{database}" |
| 42 | + ActiveRecord::Schema.define do |
| 43 | + create_table :results, force: true do |t| |
| 44 | + t.json :data |
| 45 | + headers.each { |header| t.string header } |
| 46 | + end |
| 47 | + add_index :results, :import_result if headers.include?('import_result') |
| 48 | + end |
| 49 | + csv.each_slice(5000) { |rows| print "."; Result.insert_all(rows.map(&to_record)) } |
| 50 | + puts |
| 51 | + end |
| 52 | + |
| 53 | + puts "==> Starting console for #{basename}" |
| 54 | + require "irb" |
| 55 | + IRB.conf[:IRB_NAME] = basename |
| 56 | + Result.class_eval { binding.irb(show_code: false) } |
| 57 | + end |
| 58 | +end |
| 59 | + |
| 60 | +ShopifyCSV.start(ARGV) |
0 commit comments