Skip to content
This repository
Browse code

Adding docs on the transaction context manager and transactions in

general
  • Loading branch information...
commit d8d3ff01f526c0770e40464bf8742aa013b7c666 1 parent 76523bb
Charles Leifer authored May 10, 2012

Showing 1 changed file with 64 additions and 0 deletions. Show diff stats Hide diff stats

  1. 64  docs/peewee/cookbook.rst
64  docs/peewee/cookbook.rst
Source Rendered
@@ -621,6 +621,70 @@ blogs that have no entries:
621 621
         print blog.name, ' has no entries'
622 622
 
623 623
 
  624
+Working with transactions
  625
+-------------------------
  626
+
  627
+Context manager
  628
+^^^^^^^^^^^^^^^
  629
+
  630
+You can execute queries within a transaction using the ``transaction`` context manager,
  631
+which will issue a commit if all goes well, or a rollback if an exception is raised:
  632
+
  633
+.. code-block:: python
  634
+
  635
+    db = SqliteDatabase(':memory:')
  636
+
  637
+    with transaction(db):
  638
+        blog.delete_instance(recursive=True) # delete blog and associated entries
  639
+
  640
+
  641
+Decorator
  642
+^^^^^^^^^
  643
+
  644
+Similar to the context manager, you can decorate functions with the ``commit_on_success``
  645
+decorator:
  646
+
  647
+.. code-block:: python
  648
+
  649
+    db = SqliteDatabase(':memory:')
  650
+
  651
+    @db.commit_on_success
  652
+    def delete_blog(blog):
  653
+        blog.delete_instance(recursive=True)
  654
+
  655
+
  656
+Changing autocommit behavior
  657
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  658
+
  659
+By default, databases are initialized with ``autocommit=True``, you can turn this
  660
+on and off at runtime if you like.  The behavior below is roughly the same as the
  661
+context manager and decorator:
  662
+
  663
+.. code-block:: python
  664
+
  665
+    db.set_autocommit(False)
  666
+    try:
  667
+        blog.delete_instance(recursive=True)
  668
+    except:
  669
+        db.rollback()
  670
+        raise
  671
+    else:
  672
+        db.commit()
  673
+    finally:
  674
+        db.set_autocommit(True)
  675
+
  676
+
  677
+If you would like to manually control *every* transaction, simply turn autocommit
  678
+off when instantiating your database:
  679
+
  680
+.. code-block:: python
  681
+
  682
+    db = SqliteDatabase(':memory:', autocommit=False)
  683
+
  684
+    Blog.create(name='foo blog')
  685
+    db.commit()
  686
+
  687
+
624 688
 Introspecting databases
625 689
 -----------------------
626 690
 

0 notes on commit d8d3ff0

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