Durdin
01/22/2024, 5:40 PMreferencedOn
fields on Entities
. Is there any way to know if the param has been initialized?
Example. I have this model:
class MemberEntity(id: EntityID<MemberID>) : Entity<ProjectMemberID>(id) {
var userID by MemberTable.userID
var role by MemberTable.role
/**
* Eager loaded user
*/
val user by UserEntity referencedOn MemberTable.userID
}
I have situations where i dont want my user
to be retrieved and the join being done. I can do this by hand knowing if i added the edgeload
for that param or not. However Im curious if I can know by any way if a parameter was initialized/referenced or not. So i can cast my entities to app models on a generic way without needing to know it before hand.
I saw that Table fields have an isAccesible
or isLateInit
property when accesing the reference has MemberEntity::user::isAccesible
. Yet i dont know if any of those could provide me with my solution. They still being class properties, so not something i can easily access.Chantal Loncle
02/02/2024, 9:51 PMEntity
properties: writeValues
and readValues
.
Using writeValues
is potentially the less reliable option and messier because it (most likely) requires casting. Getting the column associated with the user
field should return a value before loading references, but should return null
instead after loading:
MemberEntity.writeValues[MemberTable.userID as Column<Any?>]
This is because the collection is cleared after flushing, which may result in unexpected behavior since you won't be able to discern whether the flush is because of reference loading or something else.
readValues
is essentially a ResultRow
where the elements of writeValues
are moved after loading. If you try to get the associated value directly, the operation throws a not initialized yet
exception if reference loading hasn't happened yet:
MemberEntity.readValues[MemberTable.userID]
If you don't need to actually retrieve the field value or don't want to catch exceptions, you could try using ResultRow.hasValue()
, which returns whether or not the column has been initialized with a value. This should return true
if eager loading has already occurred:
MemberEntity.readValues.hasValue(MemberTable.userID)
If the last option works, there's a function lookupInReadValues()
that does exactly that, while also allowing you to specify behavior depending on the boolean result. It's a class-level extension function so it needs to be wrapped in an entity scope to be accessed:
MemberEntity.run {
MemberTable.userID.lookupInReadValues(
found = // do something if initialized,
notFound = // do something if not initialized
)
}
Hopefully one of these options will be useful.