agrosner / DBFlow

A blazing fast, powerful, and very simple ORM android database library that writes database code for you.
MIT License
4.88k stars 599 forks source link

HOWTO - Update table row in migration #272

Closed petroski77 closed 9 years ago

petroski77 commented 9 years ago

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

agrosner commented 9 years ago

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 commented 9 years ago

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.

petroski77 commented 9 years ago

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

petroski77 commented 9 years ago

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.