Skip to content

Commit 133dd19

Browse files
authored
chore: add tests for keep connection feature (#27)
* fix: move `db_path` & `_connection` setup ahead of any fallible ops `db_path` and `_connection` are now initialized before running code that could raise, ensuring `__del__` never touches undefined attributes even if later steps fail.
1 parent e49c354 commit 133dd19

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/mcp_server_duckdb/server.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
class DuckDBDatabase:
1818
def __init__(self, config: Config):
1919
self.config = config
20+
self.db_path = config.db_path
21+
self._connection = None
2022

2123
dir_path = config.db_path.parent
2224
if not dir_path.exists():
@@ -33,9 +35,6 @@ def __init__(self, config: Config):
3335
logger.info(f"Creating DuckDB database: {config.db_path}")
3436
duckdb.connect(config.db_path).close()
3537

36-
self.db_path = config.db_path
37-
self._connection = None
38-
3938
def connect(self):
4039
if self.config.keep_connection:
4140
if self._connection is None:

tests/test_server.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,22 @@ def test_readonly_flag_behavior():
137137

138138
result = db_ro.execute_query("SHOW TABLES;")
139139
assert result == [("ro_test",)]
140+
141+
142+
def test_temp_table_persists_with_keep_connection():
143+
with tempfile.TemporaryDirectory() as tmpdir:
144+
cfg = Config(db_path=Path(tmpdir) / "test.db", keep_connection=True, readonly=False)
145+
db = DuckDBDatabase(cfg)
146+
147+
db.execute_query("CREATE TEMP TABLE t AS SELECT 1 AS v")
148+
assert db.execute_query("SELECT v FROM t") == [(1,)]
149+
150+
151+
def test_temp_table_does_not_persist_without_keep_connection():
152+
with tempfile.TemporaryDirectory() as tmpdir:
153+
cfg = Config(db_path=Path(tmpdir) / "test.db", keep_connection=False, readonly=False)
154+
db = DuckDBDatabase(cfg)
155+
156+
db.execute_query("CREATE TEMP TABLE t AS SELECT 1 AS v")
157+
with pytest.raises(duckdb.Error):
158+
db.execute_query("SELECT v FROM t")

0 commit comments

Comments
 (0)