pardom-zz / ActiveAndroid

Active record style SQLite persistence for Android
http://www.activeandroid.com
4.71k stars 1.03k forks source link

ActiveAndroid schema migration add column that is an object #475

Open rscarson14 opened 8 years ago

rscarson14 commented 8 years ago

I apologize if this is not the place for this, I am new to SQLite and ORMs.

I am working to roll out an update for an app and need to migrate my database. Some of the tables have had columns added or removed, etc. In ActiveAndroid, schema migrations are performed by writing a migration script. It's easy for me to understand how to do this when dealing with basic data types, but I am confused how to add columns that are mapped to other objects/classes.

For example, below is an existing Model:

@Table(name = "GatewayDevices", id = BaseColumns._ID)
public class GatewayDevice extends Model {

    private static final String TAG = GatewayDevice.class.getSimpleName();

    @Column(name = "identifier", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE, notNull = true)
    private String identifier;

    @Column(name = "deviceType", notNull = true)
    private String deviceType;

    @Column(name = "name")
    private String name; 

    public GatewayDevice() {
        super();
    }

    ...

}

And I am updating it to be:

@Table(name = "GatewayDevices", id = BaseColumns._ID)
public class GatewayDevice extends Model {

    private static final String TAG = GatewayDevice.class.getSimpleName();

    @Column(name = "identifier", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE, notNull = true)
    private String identifier;

    @Column(name = "deviceType", notNull = true)
    private String deviceType;

    @Column(name = "name")
    private String name;

    @Column(name = "controller", onUpdate = Column.ForeignKeyAction.CASCADE, onDelete = Column.ForeignKeyAction.CASCADE)
    private Controller controller;

    public GatewayDevice() {
        super();
    }

    ...

}

How do I add this column using the basic ALTER TABLE GatewayDevice ADD COLUMN controller <type> structure?

uniruddh commented 8 years ago

This doc on Schema-migrations might help you.

kutukoff commented 8 years ago
public static boolean createIfNeedColumn(Class<? extends Model> type, String column) {
    boolean isFound = false;
    TableInfo tableInfo = new TableInfo(type);

    Collection<Field> columns = new TableInfo(type).getFields();
    for (Field f : columns) {
        if (column.equals(f.getName())) {
            isFound = true;
            break;
        }
    }
    if (!isFound) {
        ActiveAndroid.execSQL("ALTER TABLE " + tableInfo.getTableName() + " ADD COLUMN " + column + " TEXT;");
    }
    return isFound;
}