AmSabba
AmSabba

Reputation: 67

restructuring specific attribute in a migration in Room for android

I currently have a table in my room database that uses a string value for a specific attribute. I'm looking for a way to change that value in all rows to a new object that uses a type converter to store as JSON.

specifically im trying to change an attribute called attached_id of type string to list_of_attached, where the first item in that list is a new json object that looks like {"attached_id": "x", "type": "new item"} where x is what used to be in the attached_id attribute

Upvotes: 0

Views: 260

Answers (3)

forpas
forpas

Reputation: 164174

There is no need for concatenations which may lead to errors.
You can use the function json_object() from SQLite's JSON1 extension to create a valid JSON string and update the table:

UPDATE tablename
SET attached_id = json_object('attached_id', attached_id, 'type', 'new item');

See the demo.

Upvotes: 0

MikeT
MikeT

Reputation: 57053

I believe that the solution may be as simple as using the SQL (or even simpler doing no changes to the data (explained below)) :-

UPDATE mytable SET attached_id ='{"attached_id = : '||attached_id||'", "type": "new_item"}';

So if the attached_id column had the value 99 then it would be changed to to {"attached_id = : 99", "type": "new_item"}

However, if the above works then you could do nothing and just use a Dao that extracts the data such as SELECT '{"attached_id = : '||attached_id||'", "type": "new_item"}' AS attached_id ....

Upvotes: 1

End User
End User

Reputation: 812

As per your current implementation first, you have to retrieve the JSON update the value you want to then update the table again.

I'll suggest you should make an object of your JSON and Make use of @Embedded in the room. This will help you in case you want to query the table based on attached_id, type or sort using some fields present in json.

Please refer to this link to @Embedded

Upvotes: 1

Related Questions