Skip to content
Permalink
Browse files

`with edit(layer)` raises an error if the commit fails

  • Loading branch information
m-kuhn committed Aug 12, 2015
1 parent f647834 commit 8ab69e9386588eed90af5f09e402aa15e871015b
Showing with 16 additions and 2 deletions.
  1. +9 −1 python/core/__init__.py
  2. +7 −1 tests/src/python/test_syntactic_sugar.py
@@ -135,6 +135,13 @@ def __hash__(self):
except ImportError:
pass

class QgsEditError(Exception):
def __init__(self, value):
self.value = value

def __str__(self):
return repr(self.value)

# Define a `with edit(layer)` statement

class edit:
@@ -147,7 +154,8 @@ def __enter__(self):

def __exit__(self, ex_type, ex_value, traceback):
if ex_type is None:
assert self.layer.commitChanges()
if not self.layer.commitChanges():
raise QgsEditError(self.layer.commitErrors())
return True
else:
self.layer.rollBack()
@@ -21,7 +21,8 @@
from qgis.core import (edit,
QgsFeature,
QgsGeometry,
QgsVectorLayer
QgsVectorLayer,
QgsEditError
)

getQgisTestApp()
@@ -72,5 +73,10 @@ def testEdit(self):

assert ml.dataProvider().getFeatures().next()['value']==10

# Check that we get a QgsEditError exception when the commit fails
with self.assertRaises(QgsEditError):
with edit(ml) as l:
l.rollBack()

if __name__ == "__main__":
unittest.main()

3 comments on commit 8ab69e9

@elpaso

This comment has been minimized.

Copy link
Contributor

@elpaso elpaso replied Aug 13, 2015

Cool feature!
Just added the example to the cookbook: qgis/QGIS-Documentation@a51243b#diff-97b5c8468b99fafa1c77d39e2960b3c4

@m-kuhn

This comment has been minimized.

Copy link
Member Author

@m-kuhn m-kuhn replied Aug 13, 2015

Thanks @elpaso
I slightly modified it. I wasn't sure about the :func:with edit(layer) code. Can we add a :code:with edit(layer) or similar?

The previous version was not accurate because edit is actually an object and not a function, but that will not help the reader to get the concept so I thought it's best to mention it as a complete statement.

@elpaso

This comment has been minimized.

Copy link
Contributor

@elpaso elpaso replied Aug 13, 2015

@m-kuhn there is a :code: role for inline code but I don't know if it will be properly formatted, you can try and see what happens.

Please sign in to comment.
You can’t perform that action at this time.