Last active
April 25, 2024 19:47
-
-
Save fwarren/8a4dc4e5b9f0402d86b894e145d0d706 to your computer and use it in GitHub Desktop.
Simple sqlite3 context manager for Python 3 will type annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Open Sqlite3 databae with context manager""" | |
from pathlib import Path | |
from types import TracebackType | |
from typing import overload, Any, Optional, Union | |
class dbopen(): # pylint: disable=invalid-name | |
"""Simple context manager for sqlite3 databases""" | |
def __init__(self, path: Union[Path, str]): | |
self.path: Union[Path,str] = path | |
self.conn: Connection | |
self.cursor: Cursor | |
def __enter__(self) -> Cursor: | |
self.conn = connect(self.path) | |
self.cursor = self.conn.cursor() | |
return self.cursor | |
@overload | |
def __exit__(self, | |
exc_type: None, | |
exc_val: None, | |
exc_tb: None) -> None: | |
... | |
@overload | |
def __exit__(self, | |
exc_type: type[BaseException], | |
exc_val: BaseException, | |
exc_tb: TracebackType): | |
... | |
def __exit__(self, | |
exc_type: Optional[type[BaseException]], | |
exc_val: Optional[BaseException], | |
exc_tb: Optional[TracebackType]): | |
self.conn.commit() | |
self.conn.close() | |
if __name__ == '__main__': | |
with dbopen('./sample.db') as c: | |
c.execute("CREATE TABLE seekmap (id text, offset int, length int)") | |
c.execute("INSERT INTO seekmap VALUES ('a', 0, 2000)") | |
c.execute("INSERT INTO seekmap VALUES ('b', 2000, 3000)") | |
c.execute("SELECT * FROM seekmap") | |
result: list[Any] = c.fetchall() | |
print(result) | |
# [(u'a', 0, 2000), (u'b', 2000, 3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment