Higher DB ids should always correspond with later points in time

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the data category.

Last Updated: 2024-11-23

I had a difficult-to-debug test where I was testing access to files based on their released_on attributes.

Due to how my code was written and executed in the test env, the DB record with id: 1 was released in December and the one with id: 2, was released earlier, in November.

This situation could never have happened in production so it confused the heck out of me in this testing environment. It meant that my code to choose the latest file, which used id was a proxy for recency, failed.

   # The maximum(:id) did not correspond to the most recent entity, as I
   expected
  ZipFile.where('released_on <= ?', from.to_date)
    .where('zip_files.id = ?', maximum(:id))

# The maximum(:created_at) also failed, since I created the records out of order
# in my test environment

# What WORKED was the explicit :released_on column

  ZipFile.where('released_on <= ?', from.to_date).
    where('zip_files.released_on = ?', maximum(:released_on))

Lesson

If possible, avoid ever having database records where items with lower IDs follow afterwards in time. Including in test setups.

When generating items in a loop - even in the testing environment - try to work from past to present since it fits expectations better.