Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make fetch_val call fetch_one for type conversion #246

Merged
merged 3 commits into from
Sep 26, 2020
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