Zsolt Haraszti | dafefe1 | 2016-11-14 21:29:58 -0800 | [diff] [blame] | 1 | # |
Zsolt Haraszti | 3eb27a5 | 2017-01-03 21:56:48 -0800 | [diff] [blame] | 2 | # Copyright 2017 the original author or authors. |
Zsolt Haraszti | dafefe1 | 2016-11-14 21:29:58 -0800 | [diff] [blame] | 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | # you may not use this file except in compliance with the License. |
| 6 | # You may obtain a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | # See the License for the specific language governing permissions and |
| 14 | # limitations under the License. |
| 15 | # |
| 16 | |
| 17 | class ClosedTransactionError(Exception): |
| 18 | pass |
| 19 | |
| 20 | |
| 21 | class ConfigTransaction(object): |
| 22 | |
| 23 | __slots__ = ( |
| 24 | '_proxy', |
| 25 | '_txid' |
| 26 | ) |
| 27 | |
| 28 | def __init__(self, proxy, txid): |
| 29 | self._proxy = proxy |
| 30 | self._txid = txid |
| 31 | |
| 32 | def __del__(self): |
| 33 | if self._txid: |
| 34 | try: |
| 35 | self.cancel() |
| 36 | except: |
| 37 | raise |
| 38 | |
| 39 | # ~~~~~~~~~~~~~~~~~~~~ CRUD ops within the transaction ~~~~~~~~~~~~~~~~~~~~ |
| 40 | |
| 41 | def get(self, path='/', depth=None, deep=None): |
| 42 | if self._txid is None: |
| 43 | raise ClosedTransactionError() |
| 44 | return self._proxy.get(path, depth=depth, deep=deep, txid=self._txid) |
| 45 | |
| 46 | def update(self, path, data, strict=False): |
| 47 | if self._txid is None: |
| 48 | raise ClosedTransactionError() |
| 49 | return self._proxy.update(path, data, strict, self._txid) |
| 50 | |
| 51 | def add(self, path, data): |
| 52 | if self._txid is None: |
| 53 | raise ClosedTransactionError() |
| 54 | return self._proxy.add(path, data, self._txid) |
| 55 | |
| 56 | def remove(self, path): |
| 57 | if self._txid is None: |
| 58 | raise ClosedTransactionError() |
| 59 | return self._proxy.remove(path, self._txid) |
| 60 | |
| 61 | # ~~~~~~~~~~~~~~~~~~~~ transaction finalization ~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 62 | |
| 63 | def cancel(self): |
| 64 | """Explicitly cancel the transaction""" |
| 65 | self._proxy.cancel_transaction(self._txid) |
| 66 | self._txid = None |
| 67 | |
| 68 | def commit(self): |
| 69 | """Commit all transaction changes""" |
| 70 | try: |
| 71 | self._proxy.commit_transaction(self._txid) |
| 72 | finally: |
| 73 | self._txid = None |