Hi, are there any guides or examples, how to model relationships between sql tables and map them int...
e
Hi, are there any guides or examples, how to model relationships between sql tables and map them into data classes with sqlDelight? Something similar to Room’s @Relation
r
sqldelight supports sql views, maybe it can be implemented with it.
h
SQLDelight is "just" type-safe SQL. Like plain SQL you have to setup your relations by yourself, using foreign key. You also have to fetch the entity manually. You can use `view`s with
join
for example
e
From first glance
views
seem exactly what I need. Thank you!
k
You wouldn't necessarily need a view. You can write a query that joins tables and it'll create a new data class type for you for those results. You need to be careful about adding a lot of queries that will create a bunch of query-specific data classes, but in practice it hasn't been too bad (for me). If the data sizes are small I'll sometimes return a container with everything. So, for an
Order
and
OrderItems
have a container
data class OrderData(val order:Order, val items:List<OrderItem>)
. That involves 2 queries internally, and you need to handle it yourself, but it's not super difficult. I haven't been using Room much since 2018 or so, but prior to that, all Android ORM's were relatively unsophisticated when compared with something like Hibernate. The latter was smart enough to inflate a single join into table-specific POJOs in the right circumstances at least. All Android ORMs with referenced collections would trigger a second query to grab them, and if you weren't careful, do so in the main thread. Some would do so eager, and could be a real problem. Yada yada, I could spend hours on that. In any case, it's more explicit in sqldelight, but views or queries will create flattened data classes from table joins.