Skip to content

Commit

Permalink
Merge pull request QueueClassic#29 from jasoncodes/transaction
Browse files Browse the repository at this point in the history
Add `transaction` helper method for batch queueing.
  • Loading branch information
Ryan Smith (ace hacker) committed Dec 2, 2011
2 parents 2fcfa23 + cdaed60 commit 3972d3b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/queue_classic/database.rb
Expand Up @@ -54,6 +54,21 @@ def wait_for_notify(t)
log("done waiting for notify")
end

def transaction
begin
execute 'BEGIN'
yield
execute 'COMMIT'
rescue Exception
execute 'ROLLBACK'
raise
end
end

def transaction_idle?
connection.transaction_status == PGconn::PQTRANS_IDLE
end

def execute(sql, *params)
log("executing #{sql.inspect}, #{params.inspect}")
begin
Expand Down
29 changes: 29 additions & 0 deletions test/database_test.rb
Expand Up @@ -41,4 +41,33 @@
assert_equal [{"a"=>"123", "b"=>"456", "c"=>"579"}], result.to_a
end

def job_count
@database.execute('SELECT COUNT(*) FROM queue_classic_jobs')[0].values.first.to_i
end

test "transaction should commit" do
assert_equal true, @database.transaction_idle?
assert_equal 0, job_count
@database.transaction do
assert_equal false, @database.transaction_idle?
assert_equal 0, job_count
@database.execute "INSERT INTO queue_classic_jobs (details) VALUES ('test');"
assert_equal false, @database.transaction_idle?
assert_equal 1, job_count
end
assert_equal true, @database.transaction_idle?
assert_equal 1, job_count
end

test "transaction should rollback if there's an error" do
assert_raises RuntimeError do
@database.transaction do
@database.execute "INSERT INTO queue_classic_jobs (details) VALUES ('test');"
assert_equal 1, job_count
raise "force rollback"
end
end
assert_equal 0, job_count
end

end

0 comments on commit 3972d3b

Please sign in to comment.