diff --git a/lib/jam_ruby/connection_cleaner.rb b/lib/jam_ruby/connection_cleaner.rb index 159aea815..2bee3b57b 100644 --- a/lib/jam_ruby/connection_cleaner.rb +++ b/lib/jam_ruby/connection_cleaner.rb @@ -22,22 +22,25 @@ class ConnectionCleaner @pg_conn.transaction do |conn| + # FOR UPDATE - lock the connection and related jam_sessions in question + conn.exec("SELECT user_id FROM connections LEFT OUTER JOIN music_sessions WHERE client_id = $1 ON connections.music_session_id = music_sessions.id FOR UPDATE", [client_id]) do |result| - conn.exec("DELETE FROM connections WHERE client_id = $1 RETURNING user_id", [client_id]) do |result| - if result.cmd_tuples == 0 - # the client is already gone from the database... do nothing + conn.exec("DELETE FROM connections WHERE client_id = $1", [client_id]) do |result| - elsif result.cmd_tuples == 1 + if result.cmd_tuples == 0 + # the client is already gone from the database... do nothing - # if we did delete a row, check and see if any more connections for that user exist - # if we are down to zero, send out user gone message - conn.exec("SELECT count(user_id) FROM connections where user_id = $1", [result[0][0]]) do | result| - @mq_router.server_publish_to_user() + elsif result.cmd_tuples == 1 + + # if we did delete a row, check and see if any more connections for that user exist + # if we are down to zero, send out user gone message + conn.exec("SELECT count(user_id) FROM connections where user_id = $1", [result[0][0]]) do |result| + @mq_router.server_publish_to_user() + end + else + raise Exception 'uniqueness constraint has been lost on client_id' end - else - raise Exception 'uniqueness constraint has been lost on client_id' end - end end @@ -45,5 +48,4 @@ class ConnectionCleaner end - end \ No newline at end of file