Skip to content

Commit

Permalink
Handle early cancel
Browse files Browse the repository at this point in the history
  • Loading branch information
highker committed Aug 15, 2017
1 parent b671bc8 commit 8bfe484
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
5 changes: 5 additions & 0 deletions integration_tests/test_dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ def test_cancel_query(presto_connection):
cur.fetchall()
assert 'Query was canceled' in str(cancel_error.value)

cur = presto_connection.cursor()
with pytest.raises(Exception) as cancel_error:
cur.cancel()
assert 'Cancel query failed; no running query' in str(cancel_error.value)


def test_session_properties(run_presto):
_, host, port = run_presto
Expand Down
17 changes: 15 additions & 2 deletions prestodb/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,8 +434,10 @@ def __init__(
self._columns = None

self._finished = False
self._cancelled = False
self._request = request
self._sql = sql
self._result = PrestoResult(self)

@property
def columns(self):
Expand All @@ -445,6 +447,10 @@ def columns(self):
def stats(self):
return self._stats

@property
def result(self):
return self._result

def execute(self):
# type: () -> PrestoResult
"""Initiate a Presto query by sending the SQL statement
Expand All @@ -454,6 +460,8 @@ def execute(self):
track the rows returned by the query. To fetch all rows,
call fetch() until is_finished is true.
"""
if self._cancelled:
raise exceptions.PrestoUserError("Query has been cancelled")

response = self._request.post(self._sql)
status = self._request.process(response)
Expand All @@ -462,8 +470,8 @@ def execute(self):
self._stats.update(status.stats)
if status.next_uri is None:
self._finished = True
self.result = PrestoResult(self, status.rows)
return self.result
self._result = PrestoResult(self, status.rows)
return self._result

def fetch(self):
# type: () -> List[List[Any]]
Expand All @@ -483,6 +491,11 @@ def cancel(self):
# type: None -> None
if self.is_finished():
return

self._cancelled = True
if self._request.next_uri is None:
return

response = self._request.delete(self._request.next_uri)
if response.status_code == requests.codes.no_content:
return
Expand Down
3 changes: 3 additions & 0 deletions prestodb/dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ def __init__(

self.arraysize = 1
self._iterator = None
self._query = None

@property
def description(self):
Expand Down Expand Up @@ -245,4 +246,6 @@ def fetchall(self):
return list(self.genall())

def cancel(self):
if self._query is None:
raise OperationalError("Cancel query failed; no running query")
self._query.cancel()

0 comments on commit 8bfe484

Please sign in to comment.