Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding column in room db

I have been going through Room DB introduced in new architecture components in Android and thinking about migrating my current DBs to Room DBs.

But my current db implementation allows me to add columns to the table but as per Room, fields in POJO class represents the columns of table.

It is possible to add columns in Room DB using raw query, if yes, how shall I implement it.

like image 213
Amit Bhandari Avatar asked Jan 30 '23 00:01

Amit Bhandari


2 Answers

I know this is an old post, but this might help someone out there that needs help with this.

Do you want to add said column on an upgrade of a DB or would you like to do it on first creation of the table?

If you want to do it on an upgrade of the DB then you can look at

Migrating Room databases

Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
    .addMigrations(MIGRATION_1_2, MIGRATION_2_3).build();

static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, `name` TEXT, PRIMARY KEY(`id`))");
    }
};

static final Migration MIGRATION_2_3 = new Migration(2, 3) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE Book ADD COLUMN pub_year INTEGER");
    }
};

If you want to add the column on the fly you will have to get the instance of your DB then can try call the following:

getDatabaseInstance().query()
like image 115
Stillie Avatar answered Feb 03 '23 08:02

Stillie


There is little point for using Room with this table. After all, you cannot dynamically modify any entities or DAO methods, and so Room will not know anything about these changed columns.

If the rest of your database is Room-friendly, and you just have this one weird table, you can call getOpenHelper() on your RoomDatabase to get the SupportSQLiteOpenHelper, then work from there. The SupportSQLite... classes resemble the native Android SQLite API.

like image 38
CommonsWare Avatar answered Feb 03 '23 08:02

CommonsWare