Represents an active database transaction Transactions provide ACID guarantees for multi-statement operations. Following the rusqlite pattern: - Transactions automatically roll back when context exits - Must explicitly call commit() to persist changes - This prevents accide
| 24 | |
| 25 | |
| 26 | class Transaction: |
| 27 | """ |
| 28 | Represents an active database transaction |
| 29 | |
| 30 | Transactions provide ACID guarantees for multi-statement operations. |
| 31 | Following the rusqlite pattern: |
| 32 | - Transactions automatically roll back when context exits |
| 33 | - Must explicitly call commit() to persist changes |
| 34 | - This prevents accidentally forgetting to commit or rollback |
| 35 | |
| 36 | Examples: |
| 37 | >>> db = GraphLite.open("./mydb") |
| 38 | >>> session = db.session("admin") |
| 39 | >>> |
| 40 | >>> # Using as context manager (recommended) |
| 41 | >>> with session.transaction() as tx: |
| 42 | ... tx.execute("INSERT (p:Person {name: 'Alice'})") |
| 43 | ... tx.execute("INSERT (p:Person {name: 'Bob'})") |
| 44 | ... tx.commit() # Changes are persisted |
| 45 | >>> |
| 46 | >>> # Transaction that rolls back (no commit) |
| 47 | >>> with session.transaction() as tx: |
| 48 | ... tx.execute("INSERT (p:Person {name: 'Charlie'})") |
| 49 | ... # Automatically rolled back on context exit |
| 50 | """ |
| 51 | |
| 52 | def __init__(self, session: 'Session'): |
| 53 | """ |
| 54 | Internal constructor - use session.transaction() instead |
| 55 | |
| 56 | Begin a new transaction |
| 57 | """ |
| 58 | self._session = session |
| 59 | self._committed = False |
| 60 | self._rolled_back = False |
| 61 | |
| 62 | # Execute BEGIN TRANSACTION |
| 63 | try: |
| 64 | self._session._db.execute(self._session._session_id, "BEGIN TRANSACTION") |
| 65 | except Exception as e: |
| 66 | raise TransactionError(f"Failed to begin transaction: {e}") |
| 67 | |
| 68 | def execute(self, statement: str) -> None: |
| 69 | """ |
| 70 | Execute a GQL statement within this transaction |
| 71 | |
| 72 | Args: |
| 73 | statement: GQL statement to execute |
| 74 | |
| 75 | Raises: |
| 76 | TransactionError: If transaction is already finished or execution fails |
| 77 | |
| 78 | Examples: |
| 79 | >>> with session.transaction() as tx: |
| 80 | ... tx.execute("INSERT (p:Person {name: 'Alice'})") |
| 81 | ... tx.execute("INSERT (p:Person {name: 'Bob'})") |
| 82 | ... tx.commit() |
| 83 | """ |