Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Commit 2d0bc0f

Browse files
Make fetch_val call fetch_one for type conversion (#246)
* Make fetch_val call fetch_one for type conversion Signed-off-by: Lou Marvin Caraig <[email protected]> * Add fetch_val tests * Add the comment to explain the replacement of fetchval Co-authored-by: Vadim Markovtsev <[email protected]>
1 parent 4088e42 commit 2d0bc0f

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

databases/backends/postgres.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,17 @@ async def fetch_one(self, query: ClauseElement) -> typing.Optional[typing.Mappin
178178
async def fetch_val(
179179
self, query: ClauseElement, column: typing.Any = 0
180180
) -> typing.Any:
181-
assert self._connection is not None, "Connection is not acquired"
182-
query, args, _ = self._compile(query)
183-
return await self._connection.fetchval(query, *args, column=column)
181+
# we are not calling self._connection.fetchval here because
182+
# it does not convert all the types, e.g. JSON stays string
183+
# instead of an object
184+
# see also:
185+
# https://github.com/encode/databases/pull/131
186+
# https://github.com/encode/databases/pull/132
187+
# https://github.com/encode/databases/pull/246
188+
row = await self.fetch_one(query)
189+
if row is None:
190+
return None
191+
return row[column]
184192

185193
async def execute(self, query: ClauseElement) -> typing.Any:
186194
assert self._connection is not None, "Connection is not acquired"

tests/test_databases.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,18 @@ async def test_queries(database_url):
155155
result = await database.fetch_val(query=query)
156156
assert result == "example1"
157157

158+
# fetch_val() with no rows
159+
query = sqlalchemy.sql.select([notes.c.text]).where(
160+
notes.c.text == "impossible"
161+
)
162+
result = await database.fetch_val(query=query)
163+
assert result is None
164+
165+
# fetch_val() with a different column
166+
query = sqlalchemy.sql.select([notes.c.id, notes.c.text])
167+
result = await database.fetch_val(query=query, column=1)
168+
assert result == "example1"
169+
158170
# row access (needed to maintain test coverage for Record.__getitem__ in postgres backend)
159171
query = sqlalchemy.sql.select([notes.c.text])
160172
result = await database.fetch_one(query=query)

0 commit comments

Comments
 (0)