@@ -260,7 +260,7 @@ class Client {
260260 * @param {Query | string } query - The query to execute.
261261 * @returns A promise that resolves to a QueryResult object.
262262 */
263- async query ( query : Query | string ) : Promise < Iterator < QueryResult > > {
263+ async query ( query : Query | string , signal ?: AbortSignal ) : Promise < Iterator < QueryResult > > {
264264 const req = typeof query === 'string' ? { query} : query ;
265265 const headers : RawAxiosRequestHeaders = {
266266 [ TRINO_USER_HEADER ] : req . user ,
@@ -277,10 +277,15 @@ class Client {
277277 url : '/v1/statement' ,
278278 data : req . query ,
279279 headers : cleanHeaders ( headers ) ,
280+ // Intentionally not passing the AbortSignal on this initial request to avoid a race condition where
281+ // trino starts running the query and we never send a cancel for it
280282 } ;
281- return this . request < QueryResult > ( requestConfig ) . then (
282- result => new Iterator ( new QueryIterator ( this , result ) )
283- ) ;
283+ const createQueryRes = await this . request < QueryResult > ( requestConfig ) ;
284+ signal ?. addEventListener ( 'abort' , ( ) => {
285+ this . cancel ( createQueryRes . id ) ;
286+ } ) ;
287+
288+ return new Iterator ( new QueryIterator ( this , createQueryRes , signal ) ) ;
284289 }
285290
286291 /**
@@ -363,7 +368,8 @@ export class Iterator<T> implements AsyncIterableIterator<T> {
363368export class QueryIterator implements AsyncIterableIterator < QueryResult > {
364369 constructor (
365370 private readonly client : Client ,
366- private queryResult : QueryResult
371+ private queryResult : QueryResult ,
372+ private readonly signal ?: AbortSignal ,
367373 ) { }
368374
369375 [ Symbol . asyncIterator ] ( ) : AsyncIterableIterator < QueryResult > {
@@ -390,6 +396,7 @@ export class QueryIterator implements AsyncIterableIterator<QueryResult> {
390396
391397 this . queryResult = await this . client . request < QueryResult > ( {
392398 url : this . queryResult . nextUri ,
399+ signal : this . signal ,
393400 } ) ;
394401
395402 const data = this . queryResult . data ?? [ ] ;
@@ -418,8 +425,8 @@ export class Trino {
418425 * @param query - The query to execute.
419426 * @returns A QueryIterator object.
420427 */
421- async query ( query : Query | string ) : Promise < Iterator < QueryResult > > {
422- return this . client . query ( query ) ;
428+ async query ( query : Query | string , signal ?: AbortSignal ) : Promise < Iterator < QueryResult > > {
429+ return this . client . query ( query , signal ) ;
423430 }
424431
425432 /**
0 commit comments