Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions databases/backends/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,17 @@ async def fetch_one(self, query: ClauseElement) -> typing.Optional[typing.Mappin
async def fetch_val(
self, query: ClauseElement, column: typing.Any = 0
) -> typing.Any:
assert self._connection is not None, "Connection is not acquired"
query, args, _ = self._compile(query)
return await self._connection.fetchval(query, *args, column=column)
# we are not calling self._connection.fetchval here because
# it does not convert all the types, e.g. JSON stays string
# instead of an object
# see also:
# https://github.com/encode/databases/pull/131
# https://github.com/encode/databases/pull/132
# https://github.com/encode/databases/pull/246
row = await self.fetch_one(query)
if row is None:
return None
return row[column]

async def execute(self, query: ClauseElement) -> typing.Any:
assert self._connection is not None, "Connection is not acquired"
Expand Down
12 changes: 12 additions & 0 deletions tests/test_databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,18 @@ async def test_queries(database_url):
result = await database.fetch_val(query=query)
assert result == "example1"

# fetch_val() with no rows
query = sqlalchemy.sql.select([notes.c.text]).where(
notes.c.text == "impossible"
)
result = await database.fetch_val(query=query)
assert result is None

# fetch_val() with a different column
query = sqlalchemy.sql.select([notes.c.id, notes.c.text])
result = await database.fetch_val(query=query, column=1)
assert result == "example1"

# row access (needed to maintain test coverage for Record.__getitem__ in postgres backend)
query = sqlalchemy.sql.select([notes.c.text])
result = await database.fetch_one(query=query)
Expand Down