Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
with edit(layer) raises an error if the commit fails
  • Loading branch information
m-kuhn committed Aug 12, 2015
1 parent f647834 commit 8ab69e9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
10 changes: 9 additions & 1 deletion python/core/__init__.py
Expand Up @@ -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:
Expand All @@ -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()
Expand Down
8 changes: 7 additions & 1 deletion tests/src/python/test_syntactic_sugar.py
Expand Up @@ -21,7 +21,8 @@
from qgis.core import (edit,
QgsFeature,
QgsGeometry,
QgsVectorLayer
QgsVectorLayer,
QgsEditError
)

getQgisTestApp()
Expand Down Expand Up @@ -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
Copy link
Contributor

@elpaso elpaso commented on 8ab69e9 Aug 13, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@m-kuhn
Copy link
Member Author

@m-kuhn m-kuhn commented on 8ab69e9 Aug 13, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Copy link
Contributor

@elpaso elpaso commented on 8ab69e9 Aug 13, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.