使用自动增量字段和关系升级表

时间:2012-12-13 19:51:30

标签: android sqlite upgrade auto-increment database-relations

我有2张桌子。标题名称和详细信息的标题:

create table Headers (_id integer primary key autoincrement, name string);
create table Details (_id integer primary key autoincrement, id_headers integet, text string);

id_headers是表Headers行(一对多)的链接。 我想写一个方法来升级这些表。我知道的第一个也是最少的一个案例是创建第1和第2个表的临时表副本,创建新结构并将数据插入到新结构中。

但在这种情况下,所有“id_headers to _id”关系都将丢失。 如何将它们保持在新的结构中,同时我希望它们保持“自动增量”。

1 个答案:

答案 0 :(得分:0)

SQLiteDatabase.insert返回新的_id。首先插入Headers表数据,在temp数据结构中创建新_id与_id的映射。

现在,当您填充Details表时,请查看您的map以查找旧的id_headers值以获取新的id_headers值。         

private void migrate(SQLiteDatabase db){
    ArrayList<Header> oldHeaders = new ArrayList<Header>();
    ArrayList<Detail> oldDetails = new ArrayList<Detail>)();
    HashMap<Long,Long> idMap = new HashMap<Long,Long>();

    Cursor oldHeadersCurs = db.query("Headers", null, null, null, null, null, null);
    oldHeadersCurs.moveToFirst();

    //store the old header records
    while (!oldHeadersCurs.isAfterLast()){
        long oldId = oldHeadersCurs.getLong(oldHeadersCurs.getColumnIndex("_id"));
        String name = oldHeadersCurs.getString(oldHeadersCurs.getColumnIndex("name"));
        oldHeaders.put(new Header(oldId,name));

        oldHeadersCurs.moveToNext();
    }

    //delete the headers table
    db.execSQL("DROP TABLE Headers");
    //create the new headers table
    db.execSQL(CREATE_NEW_HEADERS_TABLE_STMT);

    //insert the header records capturing the new id
    for (Header header : oldHeaders){
        ContentValues cv = new ContentValues();
        cv.put("name", header.getName());
        long newId = db.insert("Headers", null, cv);
        idMap.put(header.getId(), newId); //mapping the old _id to the new 
    }

    //store the old detail records
    Cursor oldDetailsCurs = db.query("Details", null, null, null, null, null, null);
    oldDetailsCurs.moveToFirst();
    while (!oldDetailsCurs.isAfterLast()){
        //btw text is a data type in sqlite, you need to rename this column
        String text = oldDetailsCurs.getString(oldDetailsCurs.getColumnIndex("text"));
        long oldHeaderId = oldDetailsCurs.getLong(oldDetailsCurs.getColumnIndex("id_headers"));
        oldDetails.put(new Detail(text,oldHeaderId));
        oldDetails.moveToNext();
    }

    //recreate details table
    db.execSQL("DROP TABLE Details");
    db.execSQL("CREATE_NEW_DETAILS_TABLE_STMT");

    //insert the new detail records using the id map
    for (Detail detail : oldDetails){
        ContentValues cv = new ContentValues();
        cv.put("text",detail.getText());
        cv.put("id", idMap.get(detail.getHeaderId())); //retrieving the new _id based on the old
        db.insert("Details", null, cv);
    }
}