Tuesday, 7 January 2020

Knex migration: adding values for new column to pre-existing records

Using knex I want to add 2 additional columns to an existing table. To pre-existing records I'd like to add a value based on a calculation. Below is my migration file. It fails on the 2nd line: Cannot read property 'resolve' of undefined.

exports.up = function (knex, Promise) {
  return Promise.resolve()
    .then(function(){
            ... cut to shorten question...
    })
};

Update: I removed the Promise and now have the migration code below. This still produces two errors, probably related to the forEach loop and that it doesn't wait for one part of the loop to finish before it goes on with the next part (but I don't know how else to do the loop):

Unhandled rejection MigrationLocked: Migration table is already locked

Transaction query already complete, run with DEBUG=knex:tx for more info

const Coupon = require('../../models/coupon');
const Plan = require('../../models/plan');

exports.up = function (knex) {
    return knex.schema.table('transactions', (table) => {
      table.decimal('plan_price', 10, 2);
      table.decimal('discount', 10, 2).defaultTo(0);
    })

    .then(function(return_value){
      knex.select().from('transactions')
      .then((transactions) => {
        transactions.forEach(async function(trans){
          let original_price;
          let total_coupon_discount = 0;

          const plan = await Plan.where({id: trans.plan_id}).fetch();
          if (plan) { original_price = plan.get("price") };

          if (trans.coupon_id) {
            const coupon = await Coupon.where({id: trans.coupon_id}).fetch();
            if (coupon) {
              const amount_ex_vat = trans.amount_ex_vat;
              const couponAmount = coupon.get("discount_amount");
              original_price = amount_ex_vat + couponAmount;
              total_coupon_discount = original_price - amount_ex_vat;
            }
          }

          const promise = await knex('transactions')
          .where('id', '=', trans.id)
          .update({
            plan_price: original_price,
            discount: total_coupon_discount
          }).catch(function(error){
            console.log(error)
          }).then(function(){
            console.log('Added data to transaction record');
          })
        })
      })

      return return_value;
    })
};


from Knex migration: adding values for new column to pre-existing records

No comments:

Post a Comment