Fix the round trip count for ORM loading

Review the AI's codeEasy10 min

Your task

A latency regression came from an N+1 query: a lazy-loaded ORM relation ran 1 query for a list and then 1 more for each of its N items. An AI drafted an analogy for your PM: "a separate trip to the store for every item". Before you send it, you check the analogy against real round trip counts. You also check it does not suggest a fix that is not one, like a bigger database.

An assistant wrote count_query_round_trips(strategy, item_count, batch_size). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • strategy: the name of an ORM loading strategy.
  • item_count: how many items the list holds.
  • batch_size: how many items one batched query covers.
  • Return the number of database round trips, or -1 when strategy is not a loading strategy.

Rules the tests check:

  • Trim whitespace from strategy and lowercase it before matching.
  • A negative item_count counts as 0.
  • "lazy": 1 query for the list, plus 1 per item.
  • "eager": 1 query for the list, plus 1 query that loads every item's children at once. With 0 items, that second query is skipped.
  • "join": 1 query in total.
  • "batched": 1 query for the list, plus 1 per batch of batch_size items, rounding up. A batch_size of 0 or less counts as 1. With 0 items there are no batches.
  • Any other strategy, such as "scale_up_db", returns -1.

Examples

count_query_round_trips(strategy: str, item_count: int, batch_size: int) -> int
Example 1
Inputcount_query_round_trips("lazy", 50, 25)
Output51
Example 2
Inputcount_query_round_trips("eager", 50, 25)
Output2
Example 3
Inputcount_query_round_trips("batched", 50, 20)
Output4