DBFlow icon indicating copy to clipboard operation
DBFlow copied to clipboard

HOWTO - Update table row in migration

Open petroski77 opened this issue 11 years ago • 4 comments

Hi

I have a scenario where I need to add a new column to an existing table, and then calculate the value of the column by adding the values of two existing columns together.

The adding a new column part works flawlessly, but I cannot get it to update the column value for each row.

It's seems to get stuck in an endless loop.

    public void updateTotalDiscount() {
         new Update().table(ShoppingItem.class).set(Condition.column(ShoppingItem$Table.TOTALDISCOUNT).eq(0)).queryClose();
    }

updateTotalDiscount gets called from the migration class 's onPreMigrate() method.

Question 1: Is what I'm doing wrong? :) Question 2: In my update statement how do I get DBFlow to look at two existing columns, and then add them together for the new columns value?

ABTotalDiscount
51015
347

Best regards Christian

petroski77 avatar Jun 09 '15 10:06 petroski77

you need to use the UpdateTableMigration class and on the preMigrate() method, call the set() method as you wish.

@Override
public void onPreMigrate() {
  set(Condition.column(ShoppingItem$Table.TOTALDISCOUNT).eq(0));
}

agrosner avatar Jun 10 '15 19:06 agrosner

Using the wrapper classes during a migration to query the DB is not recommended, since we're in "opening" mode. Using the query() or queryClose() or executing any wrapper class will attempt to open the DB, which then will attempt to trigger the migration again. Results in a stackoverflow.

agrosner avatar Jun 10 '15 19:06 agrosner

Thanks @agrosner, I'll give it a try. :)

petroski77 avatar Jun 10 '15 20:06 petroski77

Hi I'm still having trouble with getting this to work. The migration gets called just fine, but the data is not updated with the correct calendar value (1970/01/01 is inserted).

Here is my migration class:

@Migration(version = 16, databaseName = AppDatabase.NAME)
    public class UpdateShoppingList extends UpdateTableMigration<ShoppingList>{

    public UpdateShoppingList() {
        super(ShoppingList.class);
    }

    @Override
    public void onPreMigrate(){
        super.onPreMigrate();
        Calendar value = Calendar.getInstance();
        set(Condition.column(ShoppingList$Table.DEADLINEDATETIME).eq(value));
    }
}

Secondly is it possible in the set statement, to set the value according to another column in the table? eg.

set(Condition.column(ShoppingList$Table.DEADLINEDATETIME).eq(ShoppingList$Table.CREATEDDATE));

I'm currently running version 2.2.1 of DBFlow.

petroski77 avatar Jul 27 '15 13:07 petroski77