uptrace / bun

SQL-first Golang ORM
https://bun.uptrace.dev
BSD 2-Clause "Simplified" License
3.65k stars 221 forks source link

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

Open john8329 opened 1 month ago

john8329 commented 1 month ago

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:

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!