Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to migrate from table without primary key using room?

I'm trying to migrate to room, but the schema of my table was like this:

CREATE TABLE cache(key text, content text, time integer);

Entity:

@Entity(tableName = "cache")
public class Cache{
    public Integer id;
    public String key;
    public String content;
    public Integer time;
}

No primary key was declared explicit, an error would occur while build:

An entity must have at least 1 field annotated with @PrimaryKey

I tried to add primary key to the table, but seems sqlite does not support that, anyone could help me?

like image 757
liuyong Avatar asked Apr 12 '18 11:04

liuyong


People also ask

Can Room primary key be NULL?

In short you cannot utilise primary keys that do not have the NOT NULL constraint, when Room builds the schema it is always applied to primary keys.

Can be used instead of the primary key?

Surrogate keys In such cases, a surrogate key can be used instead as the primary key.

Can a database table exist without a primary key?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key.


1 Answers

Excerpt from here: http://www.sqlitetutorial.net/sqlite-primary-key/

Unlike other database systems e.g., MySQL, PostgreSQL, etc., you cannot use the ALTER TABLE statement to add a primary key to an existing table.

To work around this, you need to:

  • Set the foreign key check off
  • Rename the table to another table name (old_table)
  • Create a new table (table) with the exact structure of the table you have been renamed
  • Copy data from the old_table to the table
  • Turn on the foreign key check on
like image 181
Dave Anders Avatar answered Nov 03 '22 10:11

Dave Anders