Skip to content

Commit 9672359

Browse files
committed
Address comments
Signed-off-by: Jayant Singh <[email protected]>
1 parent b6d1d67 commit 9672359

File tree

2 files changed

+32
-38
lines changed

2 files changed

+32
-38
lines changed

README.md

Lines changed: 2 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -69,34 +69,9 @@ or to a Databricks Runtime interactive cluster (e.g. /sql/protocolv1/o/123456789
6969
7070
## Transaction Support
7171

72-
The connector supports multi-statement transactions with manual commit/rollback control:
72+
The connector supports multi-statement transactions with manual commit/rollback control. Set `connection.autocommit = False` to disable autocommit mode, then use `connection.commit()` and `connection.rollback()` to control transactions.
7373

74-
```python
75-
import os
76-
from databricks import sql
77-
78-
connection = sql.connect(
79-
server_hostname=os.getenv("DATABRICKS_HOST"),
80-
http_path=os.getenv("DATABRICKS_HTTP_PATH")
81-
)
82-
83-
# Disable autocommit to use explicit transactions
84-
connection.autocommit = False
85-
86-
cursor = connection.cursor()
87-
try:
88-
cursor.execute("INSERT INTO table1 VALUES (1, 'a')")
89-
cursor.execute("INSERT INTO table2 VALUES (2, 'b')")
90-
connection.commit() # Commit both inserts atomically
91-
except Exception as e:
92-
connection.rollback() # Rollback on error
93-
raise
94-
95-
cursor.close()
96-
connection.close()
97-
```
98-
99-
For detailed information about transaction behavior, isolation levels, error handling, and best practices, see [TRANSACTIONS.md](TRANSACTIONS.md).
74+
For detailed documentation, examples, and best practices, see **[TRANSACTIONS.md](TRANSACTIONS.md)**.
10075

10176
## SQLAlchemy
10277
Starting from `databricks-sql-connector` version 4.0.0 SQLAlchemy support has been extracted to a new library `databricks-sqlalchemy`.

TRANSACTIONS.md

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ try:
5353
except Exception as e:
5454
connection.rollback() # Neither insert is saved
5555
raise
56+
finally:
57+
connection.autocommit = True # Restore default state
5658
```
5759

5860
### Rolling Back Changes
@@ -106,6 +108,8 @@ try:
106108
except Exception as e:
107109
connection.rollback() # All three inserts are discarded
108110
raise
111+
finally:
112+
connection.autocommit = True # Restore default state
109113
```
110114

111115
This is particularly useful for maintaining data consistency across related tables.
@@ -175,14 +179,19 @@ You cannot change autocommit mode while a transaction is active:
175179

176180
```python
177181
connection.autocommit = False
178-
cursor.execute("INSERT INTO logs VALUES (1, 'data')")
182+
cursor = connection.cursor()
179183

180-
# This will raise TransactionError
181184
try:
182-
connection.autocommit = True
185+
cursor.execute("INSERT INTO logs VALUES (1, 'data')")
186+
187+
# This will raise TransactionError
188+
connection.autocommit = True # Error: transaction is active
189+
183190
except sql.TransactionError as e:
184191
print(f"Cannot change autocommit: {e}")
185-
connection.rollback() # Clean up
192+
connection.rollback() # Clean up the transaction
193+
finally:
194+
connection.autocommit = True # Now it's safe to restore
186195
```
187196

188197
### Committing Without an Active Transaction
@@ -215,14 +224,19 @@ try:
215224
except Exception as e:
216225
connection.rollback() # Discard the partial transaction
217226

218-
# Now you can start a fresh transaction
219-
cursor.execute("INSERT INTO error_log VALUES (1, 'Query failed')")
220-
connection.commit()
227+
# Log the error (with autocommit still disabled)
228+
try:
229+
cursor.execute("INSERT INTO error_log VALUES (1, 'Query failed')")
230+
connection.commit()
231+
except Exception:
232+
connection.rollback()
233+
finally:
234+
connection.autocommit = True # Restore default state
221235
```
222236

223237
## Querying Server State
224238

225-
By default, the `autocommit` property returns a cached value for performance. If you need to query the server each time (for example, if you're debugging or the state might change externally):
239+
By default, the `autocommit` property returns a cached value for performance. If you need to query the server each time (for instance, when strong consistency is required):
226240

227241
```python
228242
connection = sql.connect(
@@ -291,7 +305,7 @@ conn2.commit() # Also OK
291305

292306
1. **Keep transactions short**: Long-running transactions can cause conflicts with other connections. Commit as soon as your atomic unit of work is complete.
293307

294-
2. **Always handle exceptions**: Wrap transaction code in try/except and call `rollback()` on errors.
308+
2. **Always handle exceptions**: Wrap transaction code in try/except/finally and call `rollback()` on errors.
295309

296310
```python
297311
connection.autocommit = False
@@ -305,6 +319,8 @@ except Exception as e:
305319
connection.rollback()
306320
logger.error(f"Transaction failed: {e}")
307321
raise
322+
finally:
323+
connection.autocommit = True # Restore default state
308324
```
309325

310326
3. **Use context managers**: If you're writing helper functions, consider using a context manager pattern:
@@ -331,15 +347,18 @@ with transaction(connection):
331347
# Auto-commits on success, auto-rolls back on exception
332348
```
333349

334-
4. **Reset autocommit when done**: After using explicit transactions, consider resetting autocommit to True for subsequent operations:
350+
4. **Reset autocommit when done**: Use a `finally` block to restore autocommit to `True`. This is especially important if the connection is reused or part of a connection pool:
335351

336352
```python
337353
connection.autocommit = False
338354
try:
339355
# ... transaction code ...
340356
connection.commit()
357+
except Exception:
358+
connection.rollback()
359+
raise
341360
finally:
342-
connection.autocommit = True # Reset to default
361+
connection.autocommit = True # Restore to default state
343362
```
344363

345364
5. **Be aware of isolation semantics**: Remember that repeatable read means you see a snapshot from the start of your transaction. If you need to see recent changes from other transactions, commit your current transaction and start a new one.

0 commit comments

Comments
 (0)