class SetShipmentTotalForUsersUpgrading < ActiveRecord::Migration
  def up
    # NOTE You might not need this at all unless you're upgrading from Spree 2.1.x
    # or below. For those upgrading this should populate the Order#shipment_total
    # for legacy orders
    execute "UPDATE spree_orders
             SET shipment_total = (SELECT SUM(spree_shipments.cost) AS sum_id
                                   FROM spree_shipments
                                   WHERE spree_shipments.order_id = spree_orders.id)
             WHERE spree_orders.completed_at IS NOT NULL AND spree_orders.shipment_total = 0"
  end
end

class SetShipmentTotalForUsersUpgrading < ActiveRecord::Migration
  def up
    # NOTE You might not need this at all unless you're upgrading from Spree 2.1.x
    # or below. For those upgrading this should populate the Order#shipment_total
    # for legacy orders
    Spree::Order.complete.where('shipment_total = ?', 0).includes(:shipments).find_each do |order|
      order.update_column(:shipment_total, order.shipments.sum(:cost))
    end
  end
end

Use slower but robust ActiveRecord for migration
Use slower but robust ActiveRecord for migration

When I ran this migration on my 2-1-stable store, I got the following exception:

    StandardError: An error has occurred, all later migrations canceled:

    Mysql2::Error: Column 'shipment_total' cannot be null: UPDATE spree_orders
                 SET shipment_total = (SELECT SUM(spree_shipments.cost) AS sum_id
                                       FROM spree_shipments
                                       WHERE spree_shipments.order_id = spree_orders.id)
                 WHERE spree_orders.completed_at IS NOT NULL AND spree_orders.shipment_total = 0/Users/username/appname/db/migrate/20140609012476_set_shipment_total_for_users_upgrading.spree.rb:7:in `up'
    ActiveRecord::StatementInvalid: Mysql2::Error: Column 'shipment_total' cannot be null: UPDATE spree_orders
                 SET shipment_total = (SELECT SUM(spree_shipments.cost) AS sum_id
                                       FROM spree_shipments
                                       WHERE spree_shipments.order_id = spree_orders.id)
                 WHERE spree_orders.completed_at IS NOT NULL AND spree_orders.shipment_total = 0

Rephrasing the raw SQL into ActiveRecord, the migration ran slower but didn’t crash.

(I was intending to add `if shipments && shipments.sum(:cost)` to line 7 but surprisingly didn’t need to.)

Fixes #4823
