-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_context_managers.py
More file actions
33 lines (25 loc) · 932 Bytes
/
db_context_managers.py
File metadata and controls
33 lines (25 loc) · 932 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sqlite3
from utils import SQLITE_DB_PATH
class OpenReaderCursor:
def __init__(self, sql: str, args=()):
self._SQL = sql
self.args = args
def __enter__(self) -> 'cursor':
self.conn = sqlite3.connect(SQLITE_DB_PATH)
self.cursor = self.conn.cursor()
self.cursor.execute(self._SQL, self.args)
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.cursor.close()
self.conn.close()
class OpenWriterCursor(OpenReaderCursor):
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.conn.commit()
self.cursor.close()
self.conn.close()
class OpenMultiWriterCursor(OpenWriterCursor):
def __enter__(self) -> 'cursor':
self.conn = sqlite3.connect(SQLITE_DB_PATH)
self.cursor = self.conn.cursor()
self.cursor.executemany(self._SQL, self.args)
return self.cursor