Search code examples
transactionsgoogle-cloud-spanner

How to abort deleting record when another table's record exists in Cloud Spanner?


I'm using Cloud Spanner with two tables as below.

singers singer_id

albums album_id singer_id

I need to implement two APIs DeleteSinger and CreateAlbum with Go and Spanner. Singer cannot be deleted if an album of the target singer exists and album cannot be created if singer of album's singer_id does not exist. Album can also be deleted.

I used to implement this situation in MySQL by getting exclusive lock of Singer by SELECT FOR UPDATE but how can I manage this in Spanner?

Is it good to use ReadWriteTransaction to get exclusive lock of Singer by reading and updating Singer with no values to be updated when creating albums ?


Solution

  • Cloud Spanner is a strongly consistent database, and will take care of this automatically for you without the need to explicitly lock anything. If you start a read/write transaction, and in that transaction are able to for example select a Singer, then Cloud Spanner guarantees that you can safely reference that Singer during the remainder of your transaction.

    Put another way: Instead of SELECT FOR UPDATE for the Singer(s), it is enough to just execute SELECT for the Singer(s) in your read/write transaction to get the same behavior.