Skip to content
Open
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
6 changes: 5 additions & 1 deletion pyathena/aio/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,11 @@ async def _find_previous_query_id( # type: ignore[override]
):
next_token = None
break
if execution.query == query:
if (
execution.query == query
and execution.database == self._schema_name
and (execution.catalog or "").lower() == (self._catalog_name or "").lower()
):
query_id = execution.query_id
break
if query_id or next_token is None:
Expand Down
6 changes: 5 additions & 1 deletion pyathena/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,11 @@ def _find_previous_query_id(
):
next_token = None
break
if execution.query == query:
if (
execution.query == query
and execution.database == self._schema_name
and (execution.catalog or "").lower() == (self._catalog_name or "").lower()
):
query_id = execution.query_id
break
if query_id or next_token is None:
Expand Down
83 changes: 82 additions & 1 deletion tests/pyathena/aio/test_cursor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import re
from datetime import datetime
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
Expand Down Expand Up @@ -130,6 +130,87 @@ async def test_execute_internal_legacy_kwargs_passthrough(self):
cache_expiration_time=100,
)

async def test_cache_size_different_schema(self):
"""A cached result is only reused when it ran against the same schema (#739).

Mirrors the synchronous cursor test: identical SQL can resolve to different
tables depending on the database it runs against, so a prior execution from
another schema must not be a cache hit.
"""
query = "SELECT * FROM one_row"

def execution(schema):
return AthenaQueryExecution(
{
"QueryExecution": {
"QueryExecutionId": f"query_id_{schema}",
"Query": query,
"StatementType": AthenaQueryExecution.STATEMENT_TYPE_DML,
"QueryExecutionContext": {"Database": schema},
"Status": {
"State": AthenaQueryExecution.STATE_SUCCEEDED,
"CompletionDateTime": datetime.now(timezone.utc),
},
}
}
)

cursor = AioCursor.__new__(AioCursor) # bypass __init__ to avoid AWS calls
cursor._catalog_name = None

with patch.object(
AioCursor,
"_list_query_executions",
new_callable=AsyncMock,
return_value=(None, [execution("other_schema")]),
):
cursor._schema_name = "this_schema"
assert await cursor._find_previous_query_id(query, None, cache_size=100) is None
cursor._schema_name = "other_schema"
assert (
await cursor._find_previous_query_id(query, None, cache_size=100)
== "query_id_other_schema"
)

async def test_cache_size_different_catalog(self):
query = "SELECT * FROM one_row"
schema = "this_schema"

def execution(catalog):
return AthenaQueryExecution(
{
"QueryExecution": {
"QueryExecutionId": f"query_id_{catalog}",
"Query": query,
"StatementType": AthenaQueryExecution.STATEMENT_TYPE_DML,
"QueryExecutionContext": {"Database": schema, "Catalog": catalog},
"Status": {
"State": AthenaQueryExecution.STATE_SUCCEEDED,
"CompletionDateTime": datetime.now(timezone.utc),
},
}
}
)

cursor = AioCursor.__new__(AioCursor)
cursor._schema_name = schema

with patch.object(
AioCursor,
"_list_query_executions",
new_callable=AsyncMock,
return_value=(None, [execution("awsdatacatalog")]),
):
# A different catalog must not be a cache hit.
cursor._catalog_name = "other_catalog"
assert await cursor._find_previous_query_id(query, None, cache_size=100) is None
# The same catalog, differing only in case, must still be a cache hit.
cursor._catalog_name = "AwsDataCatalog"
assert (
await cursor._find_previous_query_id(query, None, cache_size=100)
== "query_id_awsdatacatalog"
)

async def test_no_result_set_raises(self, aio_cursor):
with pytest.raises(ProgrammingError):
await aio_cursor.fetchone()
Expand Down
74 changes: 74 additions & 0 deletions tests/pyathena/test_cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,80 @@ def test_cache_expiration_time_with_cache_size(self, cursor):
assert query_id_7 != query_id_8
assert query_id_9 in [query_id_7, query_id_8]

def test_cache_size_different_schema(self):
"""A cached result is only reused when it ran against the same schema (#739).

Identical SQL can resolve to different tables depending on the database it
runs against, so a prior execution from another schema must not be a cache hit.
"""
query = "SELECT * FROM one_row"

def execution(schema):
return AthenaQueryExecution(
{
"QueryExecution": {
"QueryExecutionId": f"query_id_{schema}",
"Query": query,
"StatementType": AthenaQueryExecution.STATEMENT_TYPE_DML,
"QueryExecutionContext": {"Database": schema},
"Status": {
"State": AthenaQueryExecution.STATE_SUCCEEDED,
"CompletionDateTime": datetime.now(timezone.utc),
},
}
}
)

cursor = Cursor.__new__(Cursor) # bypass __init__ to avoid AWS calls
cursor._catalog_name = None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test approach itself looks good — it follows the same __new__ + patch.object pattern as the existing no-AWS unit tests in this file, and the negative + positive assertion pair guards against _find_previous_query_id's broad except Exception masking a setup mistake. I confirmed both new tests pass locally on this branch.

One coverage gap: with _catalog_name = None and no Catalog in the mocked execution context, the new catalog condition is only ever exercised as None == None, so the catalog half of the fix is untested. Could you extend this test (and the aio counterpart) with a catalog-mismatch case — e.g. an execution recorded with "Catalog": "some_catalog" while the cursor has a different _catalog_name? If the case-insensitive comparison suggested in pyathena/common.py is adopted, a case-difference case ("awsdatacatalog" recorded vs. "AwsDataCatalog" on the cursor, expecting a hit) would pin that behavior down too.


with patch.object(
Cursor, "_list_query_executions", return_value=(None, [execution("other_schema")])
):
cursor._schema_name = "this_schema"
assert cursor._find_previous_query_id(query, None, cache_size=100) is None
cursor._schema_name = "other_schema"
assert (
cursor._find_previous_query_id(query, None, cache_size=100)
== "query_id_other_schema"
)

def test_cache_size_different_catalog(self):
query = "SELECT * FROM one_row"
schema = "this_schema"

def execution(catalog):
return AthenaQueryExecution(
{
"QueryExecution": {
"QueryExecutionId": f"query_id_{catalog}",
"Query": query,
"StatementType": AthenaQueryExecution.STATEMENT_TYPE_DML,
"QueryExecutionContext": {"Database": schema, "Catalog": catalog},
"Status": {
"State": AthenaQueryExecution.STATE_SUCCEEDED,
"CompletionDateTime": datetime.now(timezone.utc),
},
}
}
)

cursor = Cursor.__new__(Cursor)
cursor._schema_name = schema

with patch.object(
Cursor, "_list_query_executions", return_value=(None, [execution("awsdatacatalog")])
):
# A different catalog must not be a cache hit.
cursor._catalog_name = "other_catalog"
assert cursor._find_previous_query_id(query, None, cache_size=100) is None
# The same catalog, differing only in case, must still be a cache hit
cursor._catalog_name = "AwsDataCatalog"
assert (
cursor._find_previous_query_id(query, None, cache_size=100)
== "query_id_awsdatacatalog"
)

@pytest.mark.parametrize(
"cursor",
[{"work_group": ENV.work_group, "result_reuse_enable": True, "result_reuse_minutes": 5}],
Expand Down