@@ -370,9 +370,7 @@ def __init__(
370
370
context .project = self .project_id
371
371
372
372
self .client = self .get_client ()
373
- self .bqstorage_client = _make_bqstorage_client (
374
- use_bqstorage_api , self .credentials
375
- )
373
+ self .use_bqstorage_api = use_bqstorage_api
376
374
377
375
# BQ Queries costs $5 per TB. First 1 TB per month is free
378
376
# see here for more: https://cloud.google.com/bigquery/pricing
@@ -541,29 +539,35 @@ def _download_results(
541
539
if max_results == 0 :
542
540
return None
543
541
544
- if max_results is None :
545
- # Only use the BigQuery Storage API if the full result set is requested.
546
- bqstorage_client = self .bqstorage_client
547
- else :
542
+ try :
548
543
bqstorage_client = None
544
+ if max_results is None :
545
+ # Only use the BigQuery Storage API if the full result set is requested.
546
+ bqstorage_client = _make_bqstorage_client (
547
+ self .use_bqstorage_api , self .credentials
548
+ )
549
549
550
- try :
551
550
query_job .result ()
552
551
# Get the table schema, so that we can list rows.
553
552
destination = self .client .get_table (query_job .destination )
554
553
rows_iter = self .client .list_rows (
555
554
destination , max_results = max_results
556
555
)
556
+
557
+ schema_fields = [field .to_api_repr () for field in rows_iter .schema ]
558
+ nullsafe_dtypes = _bqschema_to_nullsafe_dtypes (schema_fields )
559
+ df = rows_iter .to_dataframe (
560
+ dtypes = nullsafe_dtypes ,
561
+ bqstorage_client = bqstorage_client ,
562
+ progress_bar_type = progress_bar_type ,
563
+ )
557
564
except self .http_error as ex :
558
565
self .process_http_error (ex )
559
-
560
- schema_fields = [field .to_api_repr () for field in rows_iter .schema ]
561
- nullsafe_dtypes = _bqschema_to_nullsafe_dtypes (schema_fields )
562
- df = rows_iter .to_dataframe (
563
- dtypes = nullsafe_dtypes ,
564
- bqstorage_client = bqstorage_client ,
565
- progress_bar_type = progress_bar_type ,
566
- )
566
+ finally :
567
+ if bqstorage_client :
568
+ # Clean up open socket resources. See:
569
+ # https://github.com/pydata/pandas-gbq/issues/294
570
+ bqstorage_client .transport .channel .close ()
567
571
568
572
if df .empty :
569
573
df = _cast_empty_df_dtypes (schema_fields , df )
0 commit comments