Skip to content

Commit

Permalink
Bugfix ensure None is returned if there is no result
Browse files Browse the repository at this point in the history
Without this fix the code would instead raise an exception
incorrectly.
  • Loading branch information
pgjones committed Feb 25, 2024
1 parent 7d3fcc0 commit 83d069b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
12 changes: 8 additions & 4 deletions src/quart_db/backends/aiosqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,29 +113,33 @@ async def fetch_one(
self,
query: LiteralString,
values: Optional[Dict[str, Any]] = None,
) -> RecordType:
) -> Optional[RecordType]:
try:
async with self._lock:
async with self._connection.execute(query, values) as cursor:
row = await cursor.fetchone()
except ProgrammingError as error:
raise UndefinedParameterError(str(error))
else:
return {key: row[key] for key in row.keys()}
if row is not None:
return {key: row[key] for key in row.keys()}
return None

async def fetch_val(
self,
query: LiteralString,
values: Optional[Dict[str, Any]] = None,
) -> Any:
) -> Optional[Any]:
try:
async with self._lock:
async with self._connection.execute(query, values) as cursor:
result = await cursor.fetchone()
except ProgrammingError as error:
raise UndefinedParameterError(str(error))
else:
return result[0]
if result is not None:
return result[0]
return None

async def iterate(
self,
Expand Down
4 changes: 3 additions & 1 deletion src/quart_db/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ async def fetch_one(
pass

@abstractmethod
async def fetch_val(self, query: LiteralString, values: Optional[Dict[str, Any]] = None) -> Any:
async def fetch_val(
self, query: LiteralString, values: Optional[Dict[str, Any]] = None
) -> Optional[Any]:
"""Execute a query, returning only a value
The query accepts named arguments i.e. `:name`in the query
Expand Down
10 changes: 10 additions & 0 deletions tests/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,21 @@ async def test_fetch_one(connection: Connection) -> None:
assert result["data"] == 2


async def test_fetch_one_no_result(connection: Connection) -> None:
result = await connection.fetch_one("SELECT * FROM tbl WHERE id = -1")
assert result is None


async def test_fetch_val(connection: Connection) -> None:
value = await connection.fetch_val("SELECT 2")
assert value == 2


async def test_fetch_val_no_result(connection: Connection) -> None:
value = await connection.fetch_val("SELECT id FROM tbl WHERE id = -1")
assert value is None


async def test_iterate(connection: Connection) -> None:
await connection.execute_many(
"INSERT INTO tbl (data) VALUES (:data)",
Expand Down

0 comments on commit 83d069b

Please sign in to comment.