Skip to content

Commit

Permalink
Merge pull request #989 from quintel/migrate-fuel-prices
Browse files Browse the repository at this point in the history
Add migration for fuel prices
  • Loading branch information
grdw committed Jan 24, 2018
2 parents e505863 + b1edfbf commit e533b64
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
65 changes: 65 additions & 0 deletions db/migrate/20180117093650_fuel_prices_migration.rb
@@ -0,0 +1,65 @@
class FuelPricesMigration < ActiveRecord::Migration[5.1]
KEYS = {
costs_gas: :price_of_gas,
costs_oil: :price_of_oil,
costs_coal: :price_of_coal,
costs_biomass: :price_of_wood_pellets,
costs_co2: :price_of_co2,
costs_uranium: :price_of_uranium
}

def up
# Step 1: Select scenarios
scenarios = Scenario.where(
'(protected = ? OR created_at >= ?) AND source != ? AND title != ?',
true, 1.month.ago, 'Mechanical Turk', 'test'
)

# Step 2: Get all the start values for price_of_gas, price_of_oil, etc.
#
# This is per area
puts "#{ Time.now } | Calculating defaults"

defaults = scenarios.pluck(:area_code).uniq
.each_with_object({}) do |area_code, obj|
scenario = Scenario.new(area_code: area_code)

begin
gql = scenario.gql

obj[area_code] = KEYS.each_with_object({}) do |(key, gql_key), start|
start[key] = gql.present.query(gql_key)
end
rescue StandardError => e
puts "#{ e }"
end
end

# Step 3: Setting some timers for logging
puts "#{ Time.now } | Need to migrate #{ scenarios.count } scenarios"

migrated = 0

scenarios.find_each do |scenario|
costs = scenario.user_values.slice(*KEYS.keys)

next if !scenario.valid? || costs.empty?

if migrated % 100 == 0
puts "#{ Time.now } | Migrated: #{ migrated } - ##{ scenario.id}"
end

costs.each_pair do |key, val|
scenario.user_values[key] = (defaults[scenario.area_code][key.to_sym] * (1 + (val / 100.0)))
end

scenario.save

migrated += 1
end
end

def down
raise ActiveRecord::IrreversibleMigration
end
end
2 changes: 1 addition & 1 deletion db/schema.rb
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 20171220132741) do
ActiveRecord::Schema.define(version: 20180117093650) do

create_table "fce_values", id: :integer, force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" do |t|
t.string "using_country"
Expand Down

0 comments on commit e533b64

Please sign in to comment.