HOWTO - Update table row in migration
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?
| A | B | TotalDiscount |
|---|---|---|
| 5 | 10 | 15 |
| 3 | 4 | 7 |
Best regards Christian
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));
}
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.
Thanks @agrosner, I'll give it a try. :)
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.