Skip to content

Commit

Permalink
add simple context manager for SqliteContainer, test passing
Browse files Browse the repository at this point in the history
this allows automatic .close() to be called on connection objects.
  • Loading branch information
icyveins7 committed Mar 8, 2024
1 parent 9d983dd commit 98d68b9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
13 changes: 13 additions & 0 deletions sew/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,19 @@ def __init__(self, dbpath: str, row_factory: type=sq.Row, pragma_foreign_keys: b

if pragma_foreign_keys:
self.cur.execute("PRAGMA foreign_keys=ON")

def __enter__(self):
'''
For use in a with statement.
'''
return self

def __exit__(self, type, value, traceback):
'''
For use in a with statement.
Closes the connection for you, unlike default sqlite3.Connection.
'''
self.con.close()

#%% Mixin to redirect common sqlite methods for brevity in code later
class CommonRedirectMixin:
Expand Down
17 changes: 17 additions & 0 deletions tests/correctness.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,23 @@ def test_column_proxy_container(self):
self.assertIs(container.col2, table.columns['col2'])
self.assertIs(container.col3, table.columns['col3'])

def test_context_manager(self):
# Show that default sqlite3 doesn't close the database
with sq.connect(":memory:") as sqdb:
sqcur = sqdb.cursor()
sqcur.execute("create table x(c1 INT)")

# Then show that sew database does throw
with sew.Database(":memory:") as db:
cur = db.con.cursor()
# Extracting a cursor manually
with self.assertRaises(sq.ProgrammingError):
cur.execute('create table x(c1 INT)')
# Using our in-built executors
with self.assertRaises(sq.ProgrammingError):
db.execute('create table x(c1 INT)')



#%% ==================================== PLUGINS ==================================== #
def test_numpy_plugin(self):
Expand Down

0 comments on commit 98d68b9

Please sign in to comment.