Skip to content
Browse files

add transaction

  • Loading branch information...
1 parent ddac300 commit 269634ce6289f121607ed2c86c0495139e08a75f @siuying committed May 11, 2012
Showing with 45 additions and 6 deletions.
  1. +20 −0 README.md
  2. +2 −2 lib/nano_store/store_extension.rb
  3. +23 −4 spec/store_extension_spec.rb
View
20 README.md
@@ -92,6 +92,26 @@ user = User.find(:name, NSFEqualTo, "Bob").first
user.delete
````
+## Using Transaction
+
+Use transaction is easy, just wrap your database code in a transaction block.
+
+```ruby
+store = NanoStore.shared_store = NanoStore.store
+
+store.transaction do |the_store|
+ Animal.count.should == 0
+ obj1 = Animal.new
+ obj1.name = "Cat"
+ obj2 = Animal.new
+ obj2.name = "Dog"
+ store.changed? # => should be true at this point
+ raise "error" # => an error happened!
+end
+
+store.changed? # => should be false
+```
+
## Using Bags
A bag is a loose collection of objects stored in a document store.
View
4 lib/nano_store/store_extension.rb
@@ -127,14 +127,14 @@ def count(clazz)
end
# Create a transaction
- def transcation
+ def transaction
error_ptr = Pointer.new(:id)
beginTransactionAndReturnError(error_ptr)
raise NanoStoreError, error_ptr[0].description if error_ptr[0]
begin
yield self
- rescue e
+ rescue StandardError => e
rollbackTransactionAndReturnError(error_ptr)
raise e
end
View
27 spec/store_extension_spec.rb
@@ -69,21 +69,40 @@ class Animal < NanoStore::Model
Animal.count.should == 0
end
- it "should create a transaction and rollback when fail" do
- begin
- store = NanoStore.shared_store = NanoStore.store
+ it "should create a transaction and commit" do
+ store = NanoStore.shared_store = NanoStore.store
+ store.transaction do |the_store|
+ Animal.count.should == 0
+ obj1 = Animal.new
+ obj1.name = "Cat"
+ obj1.save
+ obj2 = Animal.new
+ obj2.name = "Dog"
+ obj2.save
+ end
+ store.save
+ Animal.count.should == 2
+ end
+
+ it "should create a transaction and rollback when fail" do
+ store = NanoStore.shared_store = NanoStore.store
+ begin
store.transaction do |the_store|
Animal.count.should == 0
obj1 = Animal.new
obj1.name = "Cat"
+ obj1.save
+
obj2 = Animal.new
obj2.name = "Dog"
- the_store.changed?.should.be.true
+ obj2.save
+
raise "error"
end
rescue
end
+ store.save
Animal.count.should == 0
end

0 comments on commit 269634c

Please sign in to comment.
Something went wrong with that request. Please try again.