Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename Realm table

I have a Gift table in my realm scheme. Now I need to rename Gift.class to UserBonus.class and add some new params(not a prob). What is the correct way to do this?

I know that realm.getTable() can return me the table, the problem is that old Giftexists in the schema but on fact I dont have Gift.class(now it is UserBonus and getTable() will return me new created table) so I cant get old gift table values and move them to new Bonus table.

The only way I see it, to left empty Gift.class and use it only for migration.

Thanks for any advice,
Yakiv

like image 201
Yakiv Mospan Avatar asked Sep 18 '15 08:09

Yakiv Mospan


2 Answers

Maybe my answer will be outdated, but now in Realm on Android there is a method 'rename', which can rename table (model) in scheme. Code will be like this:

RealmSchema schema = Realm.getInstance().getSchema();
schema.rename("OldModelName", "NewModelName"); 

And it should work!

Also you can see all features in Migration (from 25 Jun 2015) - https://github.com/realm/realm-java/pull/1239

like image 180
alena_fox_spb Avatar answered Oct 12 '22 09:10

alena_fox_spb


Currently I did implement it as follow:

  • added new UserBonus.class
  • added @Deprecated to Gift.class
  • copy all data from Gift table to UserBonus table

    // added bonus types
    Table userBonus = realm.getTable(UserBonus.class);
    userBonus.addColumn(ColumnType.STRING, "localId");
    userBonus.addColumn(ColumnType.INTEGER, "type");
    userBonus.addColumn(ColumnType.INTEGER, "date");
    userBonus.addColumn(ColumnType.STRING, "userName");
    userBonus.addColumn(ColumnType.STRING, "userNumber");
    userBonus.addColumn(ColumnType.STRING, "credits");
    
    // move Gift to UserBonus
    RealmResults<Gift> gifts = realm.where(Gift.class).findAll();
    for (Gift gift :gifts) {
        userBonus.add(
                gift.getLocalId(),
                UserBonus.TYPE_FRIEND,
                gift.getDate(),
                gift.getUserName(),
                gift.getUserNumber(),
                gift.getCredits()
        );
    }
    realm.where(Gift.class).findAll().clear();
    
like image 33
Yakiv Mospan Avatar answered Oct 12 '22 11:10

Yakiv Mospan