lundi 23 janvier 2023

Database write and read best practices ? (Java/Scala and Spanner DB)

Wondering if there's an industry standard/best practice for a situation like this - I have a method that takes in some information about a row (modeled as a case class) that has the same params as the database table. Basically, I have a method that creates an object of the class that has all the fields required to populate the db row and then once it's written to the db, I want to use the same row to do more operations. The flow looks like this:

val databaseRow = row // case class object with stuff to write to db

writeRowToDatabase(databaseRow).map {
  case Ok(_) =>
       // Row written to the database
       // Question - Should I refetch from db or safe to assume its writte to db and just use the databaseRow variable for further operations?
       // Log to different table - id of row
       logToDatabase(databaseRow.id) // can i use this `id` or should this be fetched from db?
       .
       .
       .

  case Err(err) =>
       sys.error("failed to write to db")
}

So, wondering if this is acceptable and fault tolerant? If not, what's the best practice? I could insert that row in the db and subsequently refecth it again OR just use the context object databaseRow and take the id from there to do further operations(assuming the write will succeed since I got Ok(_). This will save a call to the db. But would there be a case when I receive Ok(_) from writeToDatabase method but its not actually written to the db?? In that case, I'm logging something downstream that's not really inserted first in the db. How do folks deal with situations like this? Appreciate any pointers. Thanks

Aucun commentaire:

Enregistrer un commentaire