bun icon indicating copy to clipboard operation
bun copied to clipboard

How to tell if we fetched zero related rows or we didn't fetch them at all

Open john8329 opened this issue 1 year ago • 0 comments

Hi, I'm in the process of writing some code in a model that requires a related entity to be loaded (a calculation doing a summary), here's an example of the entity:

type Task struct {
  TaskServices []TaskService `bun:"rel:has-many"`
  ...
}
func (m *Task) GetServicesPrice() float64 {
  tot := 0
  for i := range m.TaskServices {
    tot += m.TaskServices[i].CachedPrice
  }
  return tot
}
type TaskService struct {
  TaskId int64
  Task   *Task `bun:"rel:belongs-to"`
  CachedPrice                 float64
}

(unrelated but important too: I've seen in the doc slices declared as []*Type instead of []Type, I believe the latter is the best practice since we don't require nil values in the slice, it'd be lovely if the docs were updated with this change or a good reason why we prefer slice pointers)

My problem here is the following: If I call GetServicesPrice() I expect TaskServices to be loaded. If by mistake the related entities are not fetched we risk having the function be like "sure the total is zero" without any error. What would be best in my opinion is to have a way for it to see whether:

  • We didn't load the related entity (its value is nil)
  • We loaded the entity and it has values (it's a slice)
  • We loaded the entity but there's no values ([]TaskServices{} with zero length but declared)

The scanner doesn't seem to make a difference, if it sees zero related entities it writes a nil, so in my getter there's no way to be absolutely sure we did load the related entities, and it smells like bugs waiting to happen. Javascript would have undefined for example.

What do you guys think would be best in these cases? This is a scenario that keeps happening over and over, even with the old go-pg. Having a way to programmatically assert if sub-entities are loaded or not is pretty useful in my opinion.

Thanks!

john8329 avatar Aug 26 '24 06:08 john8329