Room Android ignores #Query conditions in Dao class (Strange) - android

I am posting this because same issue is already there on stackoverflow but no solution on this. I am using Room library for db operations. I have created data classes with #Embedded and #Relation with other tables. Now the issue is when I put join queries with multiple where conditions on main as well as joined tables, it returns all/incorrect data of joined tables. This shows it ignores the conditions I have put in a DAO class query. Important thing is when I run the same query on a database externally (using stetho in chrome) it works as expected. Please help me with this as this is highly critical issue. Room version: 2.4.0
This is the data class:
data class ProductFull{
#Embedded val product: ProductMaster,
#Relation(
entity = ProductZone::class,
parentColumn = "productId",
entityColumn = "productId",
)
var productZone: ProductZone? = null,
}
This is the DAO class method:
#Query("select * from ProductMaster as pm inner join ProductZone as pz on pz.productId = pm.productId where pz.zoneId = 3")
abstract suspend fun getTempProducts(): List<ProductFull>
Above query returns data in productZone field of data class having zoneId = 1. Whereas it should only return zones having zoneId = 3.

When using #Relation room builds the underlying query(ies) to get ALL children (ProductZones) for each parent (ProductMaster) that the query selects.
A convenience annotation which can be used in a POJO to automatically fetch relation entities. When the POJO is returned from a query, all of its relations are also fetched by Room.
https://developer.android.com/reference/kotlin/androidx/room/Relation
A get-around is two have 2 dao's one that selects the parents and the other that selects the required children and a function (use an abstract class rather than an interface for the Dao's) that gets the parents using the first query and then for each parent gets the required children using the second query.
The function should be annotated with #Transaction, to allow this also annotate it with #Query("")
You would want something like:-
#Transaction
#Query("SELECT * FROM productmaster JOIN productzone on productmaster.productId = productzone.productId WHERE productzone.zoneId = 3")
abstract fun getTempProducts(): List<ProductFull>
#Query("SELECT * FROM productzone WHERE productId=:productId AND zoneId=3")
abstract fun getTempZone(productId: Long): ProductZone
#Transaction
#Query("")
fun buildFullProducts(): List<ProductFull> {
var rv = getTempProducts()
for (pf: ProductFull in rv) {
pf.productZone = getTempZone(pf.product.productId!!)
}
return rv
}
and use the buildFullProducts function to retrieve the list of ProductFull's

Related

Different accounts with different content, managing user preferences

On the bottom I added a picture of my current app structure and the current code for included data classes / entities.
At the moment in my app the user inserts the url and the code in the Login Fragment, clicking on save button the request to get the token starts. When successful the token is passed to the other requests to fetch the categories data. The different categories I get from the response are then showed in a recyclerview. By clicking on a category the user comes to the movies / seriers by genre Fragment, there I have another recyclerview with the list of movies or series.
When the token-request is successful the url & code are send also to a data class (entity) called AccountData, additional there is a unique String, put together of the url and the code, which works as Primary Key.
The AccountData is shown in a recyclerview on the Account Managment Fragment, which is the start screen of the app.
Now I want to give the user the option to select for each account, the categories he wants to have shown. Having the possibility to modify he's preferences everytime he wants.
For example:
AccountA has 10 movie categories, the user wants have shown only 5 of them.
AccountB has 15 movie categories, the user wants have shown only 6 of them.
My idea is to create a new Fragment, MovieCategorySelectFragment or so, where the user can click the categories he wants, passing the selected categories to the Movies Categories Fragment, like a Favorite-List. For implementing this I think about Room.
So I made the MovieCategory data class an Entity, using "Id" as Primary Key, and then, considering that it is a one to many relationship (I hope I am right with this), I added the Primary Key from the AccountData Entity to the MovieCategory Entity.
I made the String nullable -> val accountData: String?, that I don't get the NullpointerException error.
But now I'm stuck, would it be better to create a new data class / entity, calling it f.e. SelectedMovieCategory, and passing to it the selected item/category (from the MovieCategorySelectFragment, which is not part of a database) to it and using the room database then do display the selectet categories in the Movies Categories Fragment. Or should I make the request for the categories and save them immediately in the room-database and handling then the process of selecting?
And finally, on both methods, how can I pass the primary key from AccountData to MovieCategory? Otherwise there is no relationship between them? Do I have to create a function in the Dao to handle this?
At the end in the Account Management Fragment the user should be able to click on the account he wants to load, having loaded for each account only the categories he selected before. With the ability to change his preferences going into the MovieCategorySelectFragment and add or remove some categories from his "favorite-list".
Hopefully someone can help me to find the best and easiest way to handle this.
These are the data classes:
data class MovieCategoryResponse(
val js: List<MovieCategory>
)
#Entity
#Parcelize
data class MovieCategory(
#PrimaryKey(autoGenerate = false)
val id: String,
val number: Int,
val title: String,
val accountData: String?
) : Parcelable
#Entity
data class AccountData(
val url: String,
val code: String,
#PrimaryKey(autoGenerate = false)
val totalAccountData: String
)
It appears that you want accounts, moviecategories, seriescategories and a means of associating/relating accounts with a number of moviecategories and perhaps seriescategories and to be able to restrict the number of listed moviecategories according to an accounts preference which can change.
The solution would be a many-many relationship between account and moviecategories (and perhaps seriescategories).
However, before moving on you say:-
So I made the MovieCategory data class an Entity, using "Id" as Primary Key, and then, considering that it is a one to many relationship (I hope I am right with this), I added the Primary Key from the AccountData Entity to the MovieCategory Entity.
Regarding your hope. I believe that you are wrong. There are 3 types of relationships:-
1-1 where each row in a table would have a means of uniquely identifying the row, typically via a single column, in other table (if a separate table is apt (a single table may well suffice)). 1-1 relationships are not typically catered for by using tables.
1-many where a row in the parent table (account) could have many children (moviecategory) BUT the moviecategory could only have the 1 parent. In such a case a column in the moviecategory would contain a value that uniquely identifies the parent.
many-many an expanded 1-M that allows each side to relate to any number of the other side. So an account can relate to many moviecategories to which other accounts can relate to. The typical solution is to have an intermediate table that has 2 core columns. One that stores the value that uniquely identifies one side of the relationship and the other that stores the value that uniquely identifies the other side. Typically the 2 columns would for the primary key.
such an intermediate table has numerous terms to describe such a table, such as associative table, mapping table, reference table ....
Note how id has been highlighted. Simply creating a column called id in a table (Entity) does not make a relationship, it only supports the potential of a relationship being made.
You problem would appear to tick the boxes for a many-many relationship and thus the extra table (2 if account-secriescategories).
This table would have a column for the the value that uniquely identifies the accountData row (totalAccountData).
as the totalAccountData is the primary key (i.e. it is annotated with #PrimaryKey) and that a PrimaryKey is implicitly unique
The table would have a second column for the movieCategory's id column.
So you could start with
#Entity
data class AccountMovieMap(
val accountDataMap: String,
val movieCategoryMap: String
)
However, there is no PrimaryKey which room requires BUT the #PrimaryKey annotation only applies to a single column. If either were used then due to the implicit uniqueness the relationship would be restricted to 1-many. A composite (multiple columns/values) Primary Key is required that makes the uniqueness according to the combined values. To specify a composite PrimaryKey in Room the primaryKeys parameter of the #Entity annotation is used.
So AccountMovieMap becomes :-
#Entity(
primaryKeys = ["accountDataMap","movieCategoryMap"]
)
data class AccountMovieMap(
val accountDataMap: String,
val movieCategoryMap: String
)
As it stands there is a potential issue with the above as it is possible to insert data into either or both columns that is not a value in the respective table. That is the integrity of the relationship, in such a situation, does not exist.
SQLite and therefore Room (as with many relational database) caters for enforcing Referential Integrity. SQLite does this via ForeignKey clauses. Room uses the foreignKeys parameter of the #Entity annotation to provide a list of ForeignKeys.
In addition to enforcing referential integrity SQlite has 2 clauses ON DELETE and ON UPDATE that help to maintain referential integrity (depending upon the specified action, the most useful being CASCADE which allows changes that would break referential integrity by applying changes to the parent to the children).
Room will also warn if an index does not exist where it believe one should e.g. warning: movieCategoryMap column references a foreign key but it is not part of an index. This may trigger full table scans whenever parent table is modified so you are highly advised to create an index that covers this column. As such, the #ColumnInfo annotation can be used to add an index on the movieCategoryMap column.
So AccountMovieMap could be the fuller:-
#Entity(
primaryKeys = ["accountDataMap","movieCategoryMap"]
, foreignKeys = [
ForeignKey(
entity = AccountData::class,
parentColumns = ["totalAccountData"],
childColumns = ["accountDataMap"],
/* Optional but helps to maintain Referential Integrity */
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
),
ForeignKey(
entity = MovieCategory::class,
parentColumns = ["id"],
childColumns = ["movieCategoryMap"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
]
)
data class AccountMovieMap(
val accountDataMap: String,
#ColumnInfo(index = true)
val movieCategoryMap: String
)
To add (insert) rows you could then have/use (in an #Dao annotated class):-
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(accountMovieMap: AccountMovieMap)
noting that to avoid referential integrity conflicts that the accountData referenced/mapped and MovieCategory referenced/mapped need to exist.
As you would want to extract an AccountData's MovieCategories you need a POJO that has the AccountData with a List of MovieCategory.
This could be:-
data class AccountWithMovieCategoryList(
#Embedded
val accountData: AccountData,
#Relation(
entity = MovieCategory::class,
parentColumn = "totalAccountData", /* The column referenced in the #Embedded */
entityColumn = "id", /* The column referenced in the #Relation (MovieCategory) */
/* The mapping table */
associateBy = (
Junction(
value = AccountMovieMap::class, /* The #Entity annotated class for the mapping table */
parentColumn = "accountDataMap", /* the column in the mapping table that references the #Embedded */
entityColumn = "movieCategoryMap" /* the column in the mapping table that references the #Relation */
)
)
)
val movieCategoryList: List<MovieCategory>
)
The following could be the function in an #Dao annotated interface that retrieves an AccountWithMovieCategoryList for a given account:-
#Transaction
#Query("SELECT * FROM accountData WHERE totalAccountData=:totalAccountData")
fun getAnAccountWithMovieCategoryList(totalAccountData: String): List<AccountWithMovieCategoryList>
However Room will retrieve ALL the MovieCategories but you want to be able to specify a LIMITed number of MovieCategories for an Account, so a means is required to override Room's methodology of getting ALL mapped/associate objects.
To facilitate this then a function with a body can be used to a) get the respective AccountData and b) to then get the MovieCategory list according to the account, via the mapping table with a LIMIT specified. Thus 2 #Query functions to doe the 2 gets invoked by the overarching function.
So to get the AccountData:-
#Query("SELECT * FROM accountData WHERE totalAccountData=:totalAccountData")
fun getSingleAccount(totalAccountData: String): AccountData
And then to get the limited MovieCategories for an AccountData via (JOIN) the mapping table :-
#Query("SELECT movieCategory.* FROM accountMovieMap JOIN movieCategory ON accountMovieMap.MovieCategoryMap = movieCategory.id WHERE accountMovieMap.accountDataMap=:totalAccountData LIMIT :limit")
fun getLimitedMovieCategoriesForAnAccount(totalAccountData: String,limit: Int): List<MovieCategory>
And to put it all together aka the overarching function:-
#Transaction
#Query("")
fun getAccountWithLimitedMovieCategoryList(totalAccountData: String,categoryLimit: Int): AccountWithMovieCategoryList {
return AccountWithMovieCategoryList(
getSingleAccount(totalAccountData),
getLimitedMovieCategoriesForAnAccount(totalAccountData,categoryLimit)
)
}
Note the above code has only been compiled (so Room processing sees no issues), as such it is in-principle code
You say Best, this is opiniated and is not the best as a better way would be to utilise SQLite's more efficient handling of INTEGER primary keys.
categoryLimit i.e. an Int passed could be dynamically via the UI selected or stored and thus preserved. It could be stored in the AccountData by adding a suitable column or it could be stored elsewhere. AccountData would seem the simplest and most apt unless the expectation is that many such account based preferences should exist.
If, for example, an extra column was added to AccountData e.g. :-
#Entity
data class AccountData(
val url: String,
val code: String,
#PrimaryKey(autoGenerate = false)
val totalAccountData: String,
val movieCategoryLimit: Int /*<<<<< to store LIMIT preference */
)
A means of changing the limit would very likely be required such as the following in a/the #Dao annotated interface :-
#Query("UPDATE accountData SET movieCategoryLimit=:newLimit WHERE totalAccountData=:totalAccountData")
fun changeMovieCategoryLimit(totalAccountData: String, newLimit: Int)
A subtle change to the getAccountWithLimitedMovieCategoryList function and the LIMIT is as per the preference:-
#Transaction
#Query("")
fun getAccountWithLimitedMovieCategoryList(totalAccountData: String,categoryLimit: Int): AccountWithMovieCategoryList {
val accountData = getSingleAccount(totalAccountData)
return AccountWithMovieCategoryList(
accountData,
getLimitedMovieCategoriesForAnAccount(totalAccountData,accountData.movieCategoryLimit)
)
}
i.e. rather than using the retrieved AccountData directly, it is retrieved into a val, the val is then used to provide the AccountData and then again to provide the value for the LIMIT.
Additional
As per the comment
.... Isn't it then a one-to-many relation? ....
Then for a 1-M, as previously explained MovieCategory should have a column for storing a unique column. Which I guess is what you index the val accountData: String? to be for.
The ? should never be null (an orphan that is basically useless). Ideally, as the column use would imply selection via this column, the column should be indexed. As the intended use is as a foreign key, then although not required defining it as a foreign and enforcing referential integrity makes sense (and also goes towards describing/comment the column as a foreign key). Then the MovieCategory class could be
:-
/* MovieCategory modified for 1-m (1 account many categories)*/
#Entity(
foreignKeys = [
ForeignKey(
entity = AccountData::class,
parentColumns = ["totalAccountData"],
childColumns = ["accountData"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE,
)
]
)
#Parcelize
data class MovieCategory(
#PrimaryKey(autoGenerate = false)
val id: String,
val number: Int,
val title: String,
#ColumnInfo(index = true) /* added as likely to used for selecting rows */
val accountData: String /* should NEVER by null */
) : Parcelable
Assuming that AccountData includes the movieCategoryLimit (as explained above) then a POJO for retrieving the Account and the LIMITED list of MovieCategories would be required (a little different to the m-m equivalent) which could be:-
data class AccountDataWithMovieCategories(
#Embedded
val accountData: AccountData,
#Relation(
entity = MovieCategory::class,
parentColumn = "totalAccountData",
entityColumn = "accountData"
)
val movieCategories: List<MovieCategory>
)
i.e. no association table involved
The same issue exists that Room will retrieve ALL MovieCategories. So the following is not what you want:-
/* Note will get ALL MovieCategories (even with join and LIMIT) */
#Transaction
#Query("SELECT * FROM accountData WHERE totalAccountData=:totalAccountData")
fun getAccountWithMovieCategories(totalAccountData: String): List<AccountWithMovieCategoryList>
Rather you want to have:-
#Query("SELECT * FROM movieCategory WHERE accountData=:totalAccountData LIMIT :limit")
fun getLimitedMoviesCategoriesPerAccount(totalAccountData: String, limit: Int): List<MovieCategory>
i.e. directly accessing the MovieCategory rather than via the JOIN on the association table in the m-m version
An then finally the overarching function:-
#Transaction
#Query("")
fun getAccountWithLimitedMovieCategories(totalAccountData: String, limit: Int): AccountDataWithMovieCategories {
val accountData = getSingleAccount(totalAccountData)
return AccountDataWithMovieCategories(
accountData,
getLimitedMovieCategoriesForAnAccount(
accountData.totalAccountData,
accountData.movieCategoryLimit /* the limit as stored in the account */
)
)
}
#MikeT
Sorry for the late response...(I am using an answer because It's to long for a comment and editing my question would be messy)
I was nearly able to get everything I wanted, using this way (example series categories):
I saved the fetched categories (using retrofit) in a new POJO, named SeriesCategory:
#Entity(
foreignKeys = [
ForeignKey(
entity = AccountData::class,
parentColumns = ["totalAccountData"],
childColumns = ["accountData"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE,
)
]
)
#Parcelize
data class SeriesCategory(
#PrimaryKey(autoGenerate = false)
val id: String,
val title: String,
#ColumnInfo(index = true)
var accountData: String,
var favorite: Boolean,
val idByAccountData: String
) : Parcelable
using...
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertSeriesCategory(seriescategory: List<SeriesCategory>)
val mappedSeriesCategoryList = seriescatresponse.js.map { SeriesCategorybyAccount(it.id, it.title, totalAccountData, isFavorite, "${it.id}$totalAccountData") }
lifecycleScope.launch {
mappedSeriesCategoryList.forEach { dao.insertSeriesCategory(mappedSeriesCategoryList) }
}
In the Dao & SeriesCategoryFragment I use following code to get all categories from this specific account:
#Query("SELECT * FROM seriesCategory WHERE accountData=:totalAccountData")
fun getSeriesCategoriesPerAccount(totalAccountData: String): LiveData<List<SeriesCategory>>
viewModel.getSeriesCategoryByAccount(totalAccountData, this#SeriesCategoryFragment.requireActivity()).observe(viewLifecycleOwner) {
seriesCategoryAdapter.submitList(it)
}
As I am using a checkbox in the SeriesCategoryFragment-recyclerview I managed the checkbox in the adapter and used following code in the Dao & SelectedSeriesCategoryFragment:
#Query("SELECT * FROM seriesCategory WHERE accountData=:totalAccountData AND favorite = 1")
fun getSelectedSeriesCategoriesPerAccount(totalAccountData: String): LiveData<List<SeriesCategory>>
viewModel.getSelectedSeriesCategoryByAccount(totalAccountData, this#SeriesSelectedFragment.requireActivity()).observe(viewLifecycleOwner) {
selectedSeriesCategoryAdapter.submitList(it)
}
Thats working fine, when in the SeriesCategoryFragment a checkbox is checked(favorite = true), the category is "send" to the SelectedSeriesCategoryFragment, if it's unchecked (favorite = false) it's removed.
But at the moment I am not able to save this in my room database. So when I have for example following categories:
CategoryA, CategoryB, CategoryC, CategoryD
The user checks CategoryA and CategoryC using the checkbox, this two categories are then displayed in the SelectedSeriesCategoryFragment-recyclerview. When he unchecks the checkbox the category is removed. That's all ok.
In the same clicklistener I am using also #Update with (it = SeriesCategory):
viewModel.updateSeriesCategory(it, this#SeriesCategoryFragment.requireActivity())
Restarting the app the database shows me favorite = 1 (for true) on the categories that where checked before the restart. But the checkboxes are unchecked - an the #Query I use in the SelectedSeriesCategoryFragment (see above) doesn't seem to work anymore -> means, it is empty.
On a second restart the database shows all categories as favorite = 0 (for false) - probably because the checkbox was empty before the second restart. So as I understand, the idea I have should work - but only if the checked Checkboxes stay checked also after the restart. Can I handle this somehow with room?
Or is this a completely recyclerview-specific problem?
Eventually, my Viewholder in the Adapter looks like this:
inner class ViewHolder(val binding: RvItemSeriescategoryBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(category: SeriesCategory) {
binding.apply {
rvItemSeriescategory.text = category.title
checkboxSeriescategory.isChecked = category.favorite
checkboxSeriescategory.setOnClickListener {
if (checkboxSeriescategory.isChecked) {
category.favorite = true
onClickListener.onClick(category)
}
if (!checkboxSeriescategory.isChecked)
category.favorite = false
onClickListener.onClick(category)
}
if (category.favorite == true){
checkboxSeriescategory.isChecked = true
}
}
}
}

how to query a room database by row android kotlin

I am new to Room and it's throwing me through a loop. I am trying to take a specific row of a specific data class in my Room database and compile into a list and turn this list into a String so I can do stuff with it. I can sort of do this by printing the contents of the Room database table to the console, but that's it.
I'll show you my code that I have
this is my data class.
code.kt
#Parcelize
#Entity(tableName = "code_table")
data class code(
#PrimaryKey(autoGenerate = true)
val id: Int,
val code: String //this is the item I want to isolate
): Parcelable
a snippet of my ViewModel.kt that I use.
val readAllData: LiveData<List<code>>
private val repository: respository
init {
val Dao = database.getDatabase(application).dao()
repository = respository(Dao)
readAllData = repository.readAllData
}
a snippet of my repository.kt that I use.
val readAllData: LiveData<List<code>> = dao.readAllData()
a snippet of my Dao.kt that I use.
#Query("SELECT * FROM code_table ORDER BY id ASC")
fun readAllData(): LiveData<List<code>>
How I read the Room database table
private fun dbread(){
mUserViewModel = ViewModelProvider(this).get(ViewModel::class.java)
mUserViewModel.readAllData.observe(viewLifecycleOwner, Observer { user ->
var abc = user
println(abc)
})
}
this is what it outputs
I/System.out: [code(id=2, code=textA), code(id=3, code=textB), code(id=4, code=textC)]
I am not hell-bent on only querying the code row but I need to aggregate all the data in the code row into a string or JSON array. so, in this case, that would be the textA, textB and textC (I'm worried I haven't made myself clear)
I have also tried doing the following in the Dao
#Query("SELECT code FROM code_table")
fun readdb(): LiveData<List<code>>//I've tried this with lot different types within the Parentheses
this makes the build fail: it says the following
:app:kaptDebugKotlin 1 error
java.lang.reflect.InvocationTargetException (no error message)
I would guesstimate that this error is because the SQL syntax is off but I don't think it is.
I have also tried messing around with the ViewModel and repository to see if I can get them to only output just the code row but to no avail. I'm surprised I'm the first to post about this.
thank you for your time.
You can obtain you desidered result just by using SQL.
In Android (and with Room) you're using a SQLite database, so the most important thing is writing some SQL that is compliant with SQLite.
Then you can select the concatenation of all the values in your table, just by asking to the database to do it. You can achieve it with this:
#Query("SELECT GROUP_CONCAT(code) FROM code_table")
fun readConcatenatedCode(): LiveData<String>
The returned value will be a LiveData of String, and the String will contain all the values, concatenated.

Retrieve/insert many-to-many relationship object from Room (Kotlin)

I am working on a small project using Room. Basically a Recipe can have many Ingredients and an Ingredient can belong to many Recipes.
These are my Entities as the Documentation in the many-to-many relationship part suggested:
#Entity
data class Recipe(
var name: String
) {
#PrimaryKey(autoGenerate = true)
var recipeUID: Int = 0
}
#Entity
data class Ingredient(
var name: String
) {
#PrimaryKey(autoGenerate = true)
var ingredientUID: Int = 0
}
#Entity(primaryKeys = ["recipeUID", "ingredientUID"])
data class RecipeIngredientCrossRef(
val recipeUID: Int,
val ingredientUID: Int
)
//Docs suggested #Junction but that causes error for using tag inside #Relation...
data class RecipeWithIngredients(
#Embedded
val recipe: Recipe,
#Relation(
parentColumn = "recipeUID",
entity = Ingredient::class,
entityColumn = "ingredientUID",
associateBy = Junction(
value = RecipeIngredientCrossRef::class,
parentColumn = "recipeUID",
entityColumn = "ingredientUID"
)
)
var ingredients: List<Ingredient>
)
Then I tried to make the Dao functions following the same documentation but it only describes how to retrieve, which I applied here:
#Transaction
#Query("SELECT * FROM recipe")
suspend fun getAllRecipes(): List<RecipeWithIngredients>
Then I found this Medium article explaining what I wanted to achieve, which lead me to write this for the Insert function:
#Insert(onConflict = REPLACE)
suspend fun insert(join: RecipeIngredientCrossRef): Long
Everything works up to the insertion, I have verified that the info is being inserted, however I am doing something wrong in retrieving since it returns nothing. I can see that the reason it returns nothing is because there was nothing inserted into that table (as my insert method places it into the RecipeIngredientCrossRef table and not the recipe table), which leads me to believe the part that is wrong is in fact my insertion method.
So basically my question is: How can I retrieve a list of RecipeWithIngredients object that contains a recipe object with a list of ingredient objects as a member variable?
The documentation on Room CRUD functionality does not mention anything about this type of relationships.
I have been looking for hours on Youtube, here, the documentation and Medium but so far nothing has worked. Can someone please shed some light or point me in the right direction.
Haven't you forgot to add insert-methods for your Recipe and Ingredient tables?
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertRecipe(recipe: Recipe): Long
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertIngredient(ingredient: Ingredient): Long
So to get unempty RecipeWithIngredients result there should be three tables filled with data with your inserts from dao - Recipe, Ingredient, RecipeIngredientCrossRef. And of course they should contain id-s, that match to each other.

How to test Dao methods which return DataSource.Factory?

After shifting from SqliteOpenHelper to room in my app, I've trying to write tests for the DAO class.
My DAO looks something like this:
#Query("SELECT * FROM cards")
fun getAllCards(): List<CardData>
#Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertCard(vararg cardData: CardData): List<Long>
#Query("SELECT * FROM cards ORDER BY isRead ASC, id DESC")
fun getItemList(): DataSource.Factory<Int, CardData>
#Query("SELECT * FROM cards where instr(title, :query) > 0 ORDER BY isRead ASC, id DESC")
fun getItemList(query: String): DataSource.Factory<Int, CardData>
#Query("UPDATE cards set isRead = 1 where title = :title")
fun markRead(title: String): Int
While writing test for getAllCards, insertCard and markRead is trivial, I am still not sure how do I test the apis which return DataSource.Factory, i.e getItemList apis.
After searching on internet, I couldn't find anything related to this.
Can someone please help.
this is how I did:
val factory = dao.getItemList()
val list = (factory.create() as LimitOffsetDataSource).loadRange(0, 10)
Quoting CommonsWare
If you use paging with Room and have a #Dao method return a DataSource.Factory, the generated code uses an internal class named LimitOffsetDataSource to perform the SQLite operations and fulfill the PositionalDataSource contract.
source: https://commonsware.com/AndroidArch/previews/paging-beyond-room#head206

Room privilege Relation with query

I have two tables.
Table Decks:
Decks:
-id
-name
Table Cards:
Cards:
-id
-name
-deckId
I created a data class for this query:
data class DeckWithDueDatedCards(
#Embedded
var deckEntity: DeckEntity,
var list: List<CardEntity>
)
I removed the #Relation top of list, because it's queried all cards.
I want to add a condition. So I don't need all card, from the deck.
Let see:
I created the next Query:
#Query("SELECT *, (SELECT * FROM cards WHERE deckId = D.id AND dueDate < date('now')) as list FROM decks D WHERE D.id = :deckId")
fun getDeckWithDueDatedCards(deckId: Long): Flowable<DeckWithDueDatedCards>
But I got an error, because the inner select is bad. It can't inflate the list.
There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (sub-select returns 8 columns - expected 1)
public abstract io.reactivex.Flowable<....database.entity.DeckWithDueDatedCards> getDeckWithDueDatedCards(long deckId);
I see the issue is the Inner select have 8 item, but it's except only 1. But I have a list there. How to inflate it?
Anyone have idea how to fix this issue? It's possible with query?
Room Dao's allow non abstract method.
If you want to getDeckWithDueDatedCards you can write a method that gonna load all CardEntity first, and then load linked DeckEntity to build your DeckWithDueDatedCards
Java code :
#Query("SELECT * FROM decks WHERE id = :deckId")
public abstract DeckEntity loadDeck(int deckId);
#Query("SELECT * FROM cards WHERE deckId = D.id AND dueDate < :date")
public abstract Flowable<List<CardEntity>> loadCardEntity(String date);
#Transaction
public Flowable<DeckWithDueDatedCards> getDeckWithDueDatedCards(int deckId, String date) {
return loadCardEntity(date)
.map(cardEntityList -> {
List<DeckWithDueDatedCards> res = new ArrayList<>();
for(CardEntity cardEntity : cardEntityList) {
res.add(new DeckWithDueDatedCards(cardEntity, loadDeck(deckId)));
}
return res;
});
}
note: be aware that modification on CardEntity gonna trigger onNext on your subscriber, but modifications on DeckEntity won't ...
edit: if you need to be notify on DeckEntity changes update loadCardEntity query
#Query("SELECT cards.* FROM cards INNER JOIN decks ON cards.deckId = decks.id WHERE deckId = D.id AND dueDate < :date")
public abstract Flowable<List<CardEntity>> loadCardEntity(String date);

Categories

Resources