Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding docs on the transaction context manager and transactions in

general
  • Loading branch information...
commit d8d3ff01f526c0770e40464bf8742aa013b7c666 1 parent 76523bb
@coleifer authored
Showing with 64 additions and 0 deletions.
  1. +64 −0 docs/peewee/cookbook.rst
View
64 docs/peewee/cookbook.rst
@@ -621,6 +621,70 @@ blogs that have no entries:
print blog.name, ' has no entries'
+Working with transactions
+-------------------------
+
+Context manager
+^^^^^^^^^^^^^^^
+
+You can execute queries within a transaction using the ``transaction`` context manager,
+which will issue a commit if all goes well, or a rollback if an exception is raised:
+
+.. code-block:: python
+
+ db = SqliteDatabase(':memory:')
+
+ with transaction(db):
+ blog.delete_instance(recursive=True) # delete blog and associated entries
+
+
+Decorator
+^^^^^^^^^
+
+Similar to the context manager, you can decorate functions with the ``commit_on_success``
+decorator:
+
+.. code-block:: python
+
+ db = SqliteDatabase(':memory:')
+
+ @db.commit_on_success
+ def delete_blog(blog):
+ blog.delete_instance(recursive=True)
+
+
+Changing autocommit behavior
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+By default, databases are initialized with ``autocommit=True``, you can turn this
+on and off at runtime if you like. The behavior below is roughly the same as the
+context manager and decorator:
+
+.. code-block:: python
+
+ db.set_autocommit(False)
+ try:
+ blog.delete_instance(recursive=True)
+ except:
+ db.rollback()
+ raise
+ else:
+ db.commit()
+ finally:
+ db.set_autocommit(True)
+
+
+If you would like to manually control *every* transaction, simply turn autocommit
+off when instantiating your database:
+
+.. code-block:: python
+
+ db = SqliteDatabase(':memory:', autocommit=False)
+
+ Blog.create(name='foo blog')
+ db.commit()
+
+
Introspecting databases
-----------------------
Please sign in to comment.
Something went wrong with that request. Please try again.