领域迁移 - 将新主键初始化为int

时间:2016-10-12 05:34:46

标签: android migration realm database-migration

我是我们的应用程序,我们为其中一个元素添加了一个新的主键(实际上这是很久以前的事了)。很自然地,需要迁移。问题是,测试几乎是不可能的,因为没有人能真正说出,如何首先产生这些对象(并且无论出于何种原因,intellij都没有提供任何答案)

无论如何,这是我的迁移代码:

public class CustomMigration implements RealmMigration{

    private int currentKey = 0;

    public void migrate(DynamicRealm realm, long oldVersion, long newVersion){
        RealmSchema schema = realm.getSchema();
        if(oldVersion <= 4){}
            if(schema.contains("AvailableCandidate"){
                if(!schema.get("AvailableCandidate").hasField("pos")){
                    .addField("pos", int.class, FieldAttribute.PRIMARY_KEY)
                        .transform(new RealmObjectSchema.Function() {
                            @Override
                            public void apply(DynamicRealmObject obj) {
                                obj.setInt("pos", currentKey++);
                            }
                        });
                }
            }
            //
            //  here be more code
            //
            oldVersion = 5;
        }
    }
}

特别注意变量currentKey。我认为变换将像迭代器一样工作,每次变换迭代时都应该递增currentKey。

问题是,仍然有用户似乎得到了这个bug,貌似,currentKey没有增加。

解决这个令人讨厌的问题是什么?

编辑:结构吐出的例外情况如下:

"pos" cannot be a primary key, it already contains duplicate values: 0

1 个答案:

答案 0 :(得分:2)

只有在字段内的值不违反约束条件时,才应添加主键约束。

public class CustomMigration implements RealmMigration{

    private int currentKey = 0;

    public void migrate(DynamicRealm realm, long oldVersion, long newVersion){
        RealmSchema schema = realm.getSchema();
        if(oldVersion <= 4){}
            if(schema.contains("AvailableCandidate"){
                if(!schema.get("AvailableCandidate").hasField("pos")){
                    .addField("pos", int.class, FieldAttribute.INDEXED)
                    .transform(new RealmObjectSchema.Function() {
                        @Override
                        public void apply(DynamicRealmObject obj) {
                            obj.setInt("pos", currentKey++);
                        }
                    })
                   .addPrimaryKey("pos");
                }
            }
            //
            //  here be more code
            //
            oldVersion = 5;
        }
    }

    @Override
    public boolean equals(Object obj) {
         if(obj == null) {
             return false;
         }
         return CustomMigration.class.equals(obj.getClass());
    }

    @Override
    public int hashCode() {
         return CustomMigration.class.hashCode();
    }
}
相关问题