title: How to Conditionally Rollback a Transaction Using the PG Ruby Gem
body: <p>I am currently taking a databases course and one of the lab questions has me stumped as to how to implement the above and indeed, if it was even possible. I have tried searching the <a href="http://rubydoc.info/gems/pg/PG/Connection#transaction-instance_method">docs</a> but the transaction method defined is quite vague.</p>
  
  <p>This is the first time I have tried to do any database manipulation WITHOUT the comfort blanket of Rails and so I am a little lost. I have managed to create a connection to my postgresql database and can execute statements, the final thing that I need to do is rollback a transaction based on a simple condition.</p>
  
  <p>Allow me to show you the code:</p>
  
  <pre><code>require 'pg'
  @conn = PG::Connection.open(:dbname =&gt; 'db_15_11_labs')
  @conn.prepare('insert', 'INSERT INTO house (housenumber, street) VALUES ($1, $2) returning id')
  @words = ["Foo", "Bar", "Bash", "Bang"]
  
  def populate
    100.times.each_with_index do |i|
      # cycle through the @words array for street names, use i as house number
      ins = @conn.exec_prepared('insert', [i, "#{@words1[i % 4]} street"])
    end
  end
  </code></pre>
  
  <p>Basically, the condition is that if the returned id (<code>ins[0]['id']</code>) is even, rollback the transaction. I figure that if <code>ins[0]['id'] % 2 == 0</code> I need to throw some sort of exception but how do I do that and more importantly, how do I encode that information into the syntax given in the <a href="http://rubydoc.info/gems/pg/PG/Connection#transaction-instance_method">docs</a>?</p>
  
  <p>Thank you for your time.</p>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>I have now managed to get the syntax that will allow for the conditions to be placed within the defined transaction as follows:</p>
  
  <pre><code>@conn.transaction do |conn|
      ins = @conn.exec_prepared('insert', [i, "#{@words1[i % 100]} street"])
  end
  </code></pre>
  
  <p>and so this question really becomes more "how do I throw and catch an exception when <code>ins[0]['id'] % 2 == 0</code></p>
  
  <p>I have tried following a couple of simple tutorials on raising exceptions but doing the following:</p>
  
  <pre><code>throw :id_exception if (@ins[0]['id'].to_i % 2) == 0
      catch :id_exception do
      puts "caught :id_exception #{}"
  end
  </code></pre>
  
  <p>inside the transaction results in an <code>'throw': uncaught throw :id_exception (ArgumentError)</code></p>