-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathqueryClient.py
3543 lines (2849 loc) · 123 KB
/
queryClient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# QUERYCLIENT -- Client routines for the Data Lab Query Manager Service
'''
querymanager.queryClient
========================
Client methods for the DataLab Query Manager Service.
Query Manager Client Interface::
isAlive (svc_url=DEF_SERVICE_URL, timeout=2)
set_svc_url (svc_url)
get_svc_url ()
set_profile (profile)
get_profile ()
list_profiles (optval, token=None, profile=None, format='text')
list_profiles (token=None, profile=None, format='text')
set_timeout_request (nsec)
get_timeout_request ()
schema (value, format='text', profile=None)
schema (value='', format='text', profile=None)
services (name=None, svc_type=None, format=None,
profile='default')
query (token, query, adql=None, sql=None, fmt='csv', out=None,
async_=False, profile='default', **kw)
query (optval, adql=None, sql=None, fmt='csv', out=None,
async_=False, profile='default', **kw)
query (token=None, adql=None, sql=None, fmt='csv', out=None,
async_=False, profile='default', **kw)
status (token, jobId, profile='default')
status (optval, jobId=None, profile='default')
status (token=None, jobId=None, profile='default')
jobs (token, jobId, status='all', option='list')
jobs (optval, jobId=None, status='all', option='list')
jobs (token=None, jobId=None, status='all', option='list')
results (token, jobId, delete=True, profile='default')
results (optval, jobId=None, delete=True, profile='default')
results (token=None, jobId=None, delete=True, profile='default')
error (token, jobId, profile='default')
error (optval, jobId=None, profile='default')
error (token=None, jobId=None, profile='default')
abort (token, jobId, profile='default')
abort (optval, jobId=None, profile='default')
abort (token=None, jobId=None, profile='default')
wait (token, jobId, wait=3, verbose=False,
profile='default')
wait (optval, jobId=None, wait=3, verbose=False,
profile='default')
wait (token=None, jobId=None, wait=3, verbose=False,
profile='default')
mydb_list (optval, table=None, **kw)
mydb_list (table=None, token=None, **kw)
mydb_create (token, table, schema, **kw)
mydb_create (table, schema, token=None, **kw)
mydb_insert (token, table, data, **kw)
mydb_insert (table, data, token=None, **kw)
mydb_import (token, table, data, **kw)
mydb_import (table, data, token=None, **kw)
mydb_truncate (token, table)
mydb_truncate (table, token=None)
mydb_index (token, table, column)
mydb_index (table, column, token=None)
mydb_drop (token, table)
mydb_drop (table, token=None)
mydb_rename (token, source, target)
mydb_rename (source, target, token=None)
mydb_copy (token, source, target)
mydb_copy (source, target, token=None)
list (token, table) # DEPRECATED
list (optval, table=None) # DEPRECATED
list (table=None, token=None) # DEPRECATED
drop (token, table) # DEPRECATED
drop (optval, table=None) # DEPRECATED
drop (table=None, token=None) # DEPRECATED
Import via:
.. code-block:: python
from dl import queryClient
'''
from __future__ import print_function
__authors__ = 'Mike Fitzpatrick <[email protected]>, Matthew Graham <[email protected]>, Data Lab <[email protected]>'
try:
from querymanager.__version__ import __version__
except ImportError as e:
from dl.__version__ import __version__
import requests
try:
from urllib import quote_plus # Python 2
except ImportError:
from urllib.parse import quote_plus # Python 3
try:
from cStringIO import StringIO
except:
from io import StringIO # Python 2/3 compatible
from io import BytesIO
import socket
import json
import time
import os
import sys
import collections
import ast, csv
import pandas
import pycurl
import certifi
from tempfile import NamedTemporaryFile
from dl import resClient
from dl import storeClient
from dl.helpers.utils import convert
if os.path.isfile('./Util.py'): # use local dev copy
from Util import multimethod
from Util import def_token, is_auth_token, split_auth_token
from Util import validTableName
else: # use distribution copy
from dl.Util import multimethod
from dl.Util import def_token, is_auth_token, split_auth_token
from dl.Util import validTableName
is_py3 = sys.version_info.major == 3
# ####################################
# Query Manager Configuration
# ####################################
# The URL of the QueryManager service to contact. This may be changed by
# passing a new URL into the set_svc_url() method before beginning.
DEF_SERVICE_ROOT = 'https://datalab.noirlab.edu'
DAL_SERVICE_URL = 'https://datalab.noirlab.edu' # The base DAL service URL
# Allow the service URL for dev/test systems to override the default.
THIS_HOST = socket.gethostname() # host name
sock = socket.socket(type=socket.SOCK_DGRAM) # host IP address
sock.connect(('8.8.8.8', 1)) # Example IP address, see RFC 5737
THIS_IP, _ = sock.getsockname()
if THIS_HOST[:5] == 'dldev':
DEF_SERVICE_ROOT = 'https://dldev.datalab.noirlab.edu'
elif THIS_HOST[:6] == 'dltest':
DEF_SERVICE_ROOT = 'https://dltest.datalab.noirlab.edu'
DEF_SERVICE_URL = DEF_SERVICE_ROOT + '/query'
SM_SERVICE_URL = DEF_SERVICE_ROOT + '/storage'
RM_SERVICE_URL = DEF_SERVICE_ROOT + '/res'
# The requested query 'profile'. A profile refers to the specific
# machines and services used by the QueryManager on the server.
DEF_SERVICE_PROFILE = 'default'
# Use a /tmp/QM_DEBUG file as a way to turn on debugging in the client code.
DEBUG = os.path.isfile('/tmp/QM_DEBUG')
# Check for a file to override the default service URL.
if os.path.exists('/tmp/QM_SVC_URL'):
with open('/tmp/QM_SVC_URL') as fd:
DEF_SERVICE_URL = fd.read().strip()
if os.path.exists('/tmp/SM_SVC_URL'):
with open('/tmp/SM_SVC_URL') as fd:
SM_SERVICE_URL = fd.read().strip()
if os.path.exists('/tmp/RM_SVC_URL'):
with open('/tmp/RM_SVC_URL') as fd:
RM_SERVICE_URL = fd.read().strip()
# Default Sync query timeout default (300sec)
DEF_TIMEOUT_REQUEST = 300
#####################################################################
# START - supporting functions for pycurl download code
def human_readable_size(size, decimal_places=2):
"""
Converts a size in bytes to a human-readable format (e.g., KB, MB, GB).
:param size: Size in bytes.
:param decimal_places: Number of decimal places to format.
:return: Human-readable size string.
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:
if size < 1024.0:
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
def human_readable_time(seconds, decimal_places=2):
"""
Converts time in seconds to a human-readable format (hours:minutes:seconds).
:param seconds: Time in seconds.
:param decimal_places: Number of decimal places for the seconds part.
:return: Human-readable time string.
"""
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
if hours > 0:
return f"{int(hours)}h:{int(minutes)}m:{seconds:.{decimal_places}f}s"
elif minutes > 0:
return f"{int(minutes)}m:{seconds:.{decimal_places}f}s"
else:
return f"{seconds:.{decimal_places}f}s"
def progress_report(download_t, download_d, upload_t, upload_d):
"""
Callback function to report the progress of a download or upload operation.
This function is designed to be used with pycurl to periodically report the
progress of file transfer operations. It prints updates to the console at
intervals specified by the `progress.report_interval`.
Parameters:
- download_t (int): Total size of the download in bytes.
- download_d (int): Number of bytes downloaded so far.
- upload_t (int): Total size of the upload in bytes (not used in this context).
- upload_d (int): Number of bytes uploaded so far (not used in this context).
"""
now = time.time() # Current time for calculating the interval and rate.
# Check if it's time to report progress (based on the specified interval).
if now - progress_report.last_report_time >= progress_report.report_interval:
elapsed_time = now - progress_report.start_time # Total time elapsed since the start of the download.
# Calculate the download rate in kilobytes per second.
rate = download_d / elapsed_time / 1024
# Print the progress update, showing the amount downloaded, time elapsed, and current download rate.
print(
f"\rDownloaded {human_readable_size(download_d)} in"
f" {human_readable_time(elapsed_time)} at {rate:.2f} KB/s",
end="")
progress_report.last_report_time = now # Update the last report time to the current time.
def setup_progress():
"""
Setup the progress reporting.
"""
progress_report.start_time = time.time()
progress_report.last_report_time = progress_report.start_time
progress_report.report_interval = 5 # seconds between reports
# END - Supporting functions for pycurl download code
#####################################################################
# ####################################################################
# Query Client error class
# ####################################################################
class queryClientError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class DLHTTPException(Exception):
def __init__(self, status_code, message):
self.status_code = status_code
self.error_message = message
super().__init__(f"DL HTTP Error {status_code}: {message}")
# ####################################################################
# Module Functions
# ####################################################################
# --------------------------------------------------------------------
# ISALIVE -- Ping the Query Manager service to see if it responds.
#
def isAlive(svc_url=DEF_SERVICE_URL, timeout=5):
return qc_client.isAlive(svc_url=svc_url, timeout=timeout)
# --------------------------------------------------------------------
# SET_SVC_URL -- Set the Query Manager ServiceURL to call.
#
def set_svc_url(svc_url):
return qc_client.set_svc_url(svc_url)
# --------------------------------------------------------------------
# GET_SVC_URL -- Get the Query Manager ServiceURL being called.
#
def get_svc_url():
return qc_client.get_svc_url()
# --------------------------------------------------------------------
# SET_PROFILE -- Set the Query Manager service profile to be used.
#
def set_profile(profile):
return qc_client.set_profile(profile)
# --------------------------------------------------------------------
# GET_PROFILE -- Get the Query Manager service profile being used.
#
def get_profile():
return qc_client.get_profile()
# -----------------------------
# Utility Functions
# -----------------------------
# --------------------------------------------------------------------
# LIST_PROFILES -- List the available service profiles.
#
@multimethod('qc',1,False)
def list_profiles(optval, token=None, profile=None, format='text'):
if optval is not None and is_auth_token(optval):
# optval looks like a token
return qc_client._list_profiles (token=def_token(optval),
profile=profile, format=format)
else:
# optval looks like a profile name
return qc_client._list_profiles (token=def_token(token), profile=optval,
format=format)
@multimethod('qc',0,False)
def list_profiles(token=None, profile=None, format='text'):
'''Retrieve the profiles supported by the query manager service.
Usage::
list_profiles (token=None, profile=None, format='text')
MultiMethod Usage::
queryClient.list_profiles (token)
queryClient.list_profiles ()
Parameters
----------
token : str [Optional]
Authentication token (see function :func:`authClient.login()`).
profile : str
A specific profile configuration to list. If ``None``, a list of
profiles available to the given auth token is returned.
format : str
Result format: One of 'text' or 'json'.
Returns
-------
profiles : list or dict
A list of the names of the supported profiles or a dictionary of
the specific profile.
Example
-------
.. code-block:: python
profiles = queryClient.list_profiles()
profiles = queryClient.list_profiles(token)
'''
return qc_client._list_profiles (token=def_token(token), profile=profile,
format=format)
# --------------------------------------------------------------------
# SET_TIMEOUT_REQUEST -- Set the Synchronous query timeout value (in sec).
#
def set_timeout_request(nsec):
return qc_client.set_timeout_request (nsec)
# --------------------------------------------------------------------
# GET_TIMEOUT_REQUEST -- Get the Synchronous query timeout value (in sec).
#
def get_timeout_request():
return qc_client.get_timeout_request ()
# --------------------------------------------------------------------
# SCHEMA -- Return information about a data service schema value.
#
@multimethod('qc',1,False)
def schema(value, format='text', profile=None):
return qc_client._schema (value=value, format=format, profile=profile)
@multimethod('qc',0,False)
def schema(value='', format='text', profile=None):
'''[DEPRECATED] Return information about a data service schema.
Usage::
schema (value='', format='text', profile=None)
Parameters
----------
value : str
Schema object to return: Of the form <schema>[.<table>[.<column]].
profile : str
The name of the service profile to use. The list of available
profiles can be retrieved from the service (see function
:func:`queryClient.list_profiles()`).
format : str
Result format: One of 'text' or 'json' (NOT CURRENTLY USED).
Returns
-------
Anything?
'''
return qc_client._schema (value=value, format=format, profile=profile)
# --------------------------------------------------------------------
# SERVICES -- List public storage services
#
def services(name=None, svc_type=None, mode='list', profile='default'):
'''Search or list available data services.
Usage::
services (name=None, svc_type=None, mode='list', profile='default')
Parameters
----------
name : str
Schema object to return: Of the form <schema>[.<table>[.<column]].
svc_type : str
Limit results to specified service type. Supported options are
'tap', 'sia', 'scs', or 'vos'.
mode : str
Print output as either 'list' or 'resolve'.
profile : str
The name of the service profile to use. The list of available
profiles can be retrieved from the service (see function
:func:`queryClient.list_profiles()`).
Returns
-------
If mode is 'list' then a human-readable list of matching services is
returned. If mode is 'resolve' then a JSON string of matching services
is returned un the form "{<svc_name> : <svc_url>, ....}".
Example
-------
.. code-block:: python
# List the available SIA services
queryClient.services(svc_type="sia")
# List the available USNO services, note the '%' matching metacharacter
queryClient.services(name="usno%")
# Get the serviceURL of the USNO-A2 table
queryClient.services(name="usno/a2", mode="resolve")
'''
return qc_client.services (name=name, svc_type=svc_type, mode=mode,
profile=profile)
# -----------------------------
# Query Functions
# -----------------------------
# --------------------------------------------------------------------
# QUERY -- Send a query to the Query Manager service
#
@multimethod('qc',2,False)
def query(token, query, adql=None, sql=None, fmt='csv', out=None,
async_=False, drop=False, profile='default', **kw):
return qc_client._query (token=def_token(token), adql=adql, sql=query,
fmt=fmt, out=out, async_=async_, drop=drop,
profile=profile, **kw)
@multimethod('qc',1,False)
def query(optval, adql=None, sql=None, fmt='csv', out=None, async_=False, drop=False,
token=None, profile='default', **kw):
if optval is not None and optval.lower()[:6] == 'select':
# optval looks like a query string
return qc_client._query (token=def_token(None), adql=adql, sql=optval,
fmt=fmt, out=out, async_=async_, drop=drop,
profile=profile, **kw)
else:
# optval is (probably) a token
return qc_client._query (token=def_token(optval), adql=adql, sql=sql,
fmt=fmt, out=out, async_=async_, drop=drop,
profile=profile, **kw)
@multimethod('qc',0,False)
def query(token=None, adql=None, sql=None, fmt='csv', out=None, async_=False, drop=False,
profile='default', **kw):
'''Send an SQL or ADQL query to the database or TAP service.
Usage::
query (token=None, adql=None, sql=None, fmt='csv', out=None,
async_=False, drop=False, profile='default', **kw):
MultiMethod Usage::
queryClient.query (token, query, <args>)
queryClient.query (token | query, <args>)
Parameters
----------
token : str [Optional]
Authentication token (see function :func:`authClient.login()`).
adql : str or None
ADQL query string that will be passed to the DB query manager, e.g.
.. code-block:: python
adql='select top 3 ra,dec from gaia_dr3.gaia_source'
sql : str or None
SQL query string that will be passed to the DB query manager, e.g.
.. code-block:: python
sql='select ra,dec from gaia_dr3.gaia_source limit 3'
fmt : str
Format of result to be returned by the query. Permitted values are:
* 'csv' The returned result is a comma-separated string
that looks like a csv file (newlines at the end
of every row) [DEFAULT].
* 'csv-noheader' A csv result with no column headers (data only).
* 'ascii' Same, but the column separator is a tab \t.
* 'array' Returns a NumPy array.
* 'pandas' Returns a Pandas DataFrame.
* 'structarray' Numpy structured array (aka 'record array').
* 'table' Returns an Astropy Table object.
The following formats may be used when saving a file to
virtual storage on the server:
* 'fits' FITS binary.
* 'votable' An XML-formatted VOTable.
out : str or None
The output filename to create on the local machine, the URI of a
VOSpace or MyDB resource to create, or ``None`` if the result is
to be returned directly to the caller.
async_ : bool
If ``True``, the query is Asynchronous, i.e. a job is submitted to
the DB, and a jobID token is returned the caller. The jobID must
be then used to check the query's status and to retrieve the result
(when the job status is ``COMPLETED``) or the error message (when
the job status is ``ERROR``). Default is ``False``, i.e. the task
runs a Synchroneous query.
``async_`` replaces the previous ``async`` parameter, because ``async``
was promoted to a keyword in Python 3.7. Users of Python versions
prior to 3.7 can continue to use the ``async`` keyword.
drop : bool
If ``True``, then if the query is saving to MyDB where the same table
name already exists, it will overwrite the old MyDB table.
profile : str or None
The Query Manager profile to use for this call. If ``None`` then
the default profile is used. Available profiles may be listed
using the :func:`queryClient.list_profiles()`.
**kw : dict
Optional keyword arguments. Supported keywords currently include:
wait = False
Wait for Asynchronous queries to complete? If enabled,
the query() method will submit the job in Async mode
and then poll for results internally before returning.
The default is to return the job ID immediately and let
the client poll for job status and return results.
timeout = 300
Requested timeout (in seconds) for a query. For a Sync
query, this value sets a session timeout request in the
database that will abort the query at the specified time.
A maximum value of 600 seconds is permitted. If the
``wait`` option is enabled for an Async query, this is the
maximum time the query will be allowed to run before an
abort() is issued on the job. The maximum timeout for
an Async job is 24-hrs (86400 sec).
poll = 1
Async job polling time in seconds.
verbose = False
Print verbose messages during Async job.
Returns
-------
result : str
If ``async_=False``, the return value is the result of the
query as a formatted string (see ``fmt``). Otherwise the
result string is a job token, with which later the
Asynchronous query's status can be checked
(:func:`queryClient.status()`), and the result retrieved (see
:func:`queryClient.result()`).
Example
-------
.. code-block:: python
query = 'select ra,dec from gaia_dr3.gaia_source limit 3'
response = queryClient.query(adql=query, fmt='csv')
print (response)
This prints
.. code::
ra,dec
314.14738713961134,37.33643208345386
314.1588238386895,37.33682543157976
314.1519366421579,37.33533842266872
'''
return qc_client._query (token=def_token(token), adql=adql, sql=sql,
fmt=fmt, out=out, async_=async_, drop=drop,
profile=profile,
**kw)
# --------------------------------------------------------------------
# STATUS -- Get the status of an Asynchronous query
#
@multimethod('qc',2,False)
def status(token, jobId, profile='default'):
return qc_client._status (token=def_token(token), jobId=jobId,
profile=profile)
@multimethod('qc',1,False)
def status(optval, jobId=None, profile='default'):
if optval is not None and is_auth_token(optval):
# optval looks like a token
return qc_client._status (token=def_token(optval), jobId=jobId,
profile=profile)
else:
# optval is probably a jobId
return qc_client._status (token=def_token(None), jobId=optval,
profile=profile)
@multimethod('qc',0,False)
def status(token=None, jobId=None, profile='default'):
'''Get the status of an Asynchronous query.
Usage::
status (token=None, jobId=None)
MultiMethod Usage::
queryClient.status (jobId)
queryClient.status (token, jobId)
queryClient.status (token, jobId=<id>)
queryClient.status (jobId=<str>)
Use the authentication token and the jobId of a previously issued
Asynchronous query to check the query's current status.
Parameters
----------
token : str [Optional]
Authentication token (see function :func:`authClient.login()`).
jobId : str
The jobId returned when issuing an Asynchronous query via
:func:`queryClient.query()` with ``async_=True``.
Returns
-------
status : str
Either ``QUEUED`` or ``EXECUTING`` or ``COMPLETED``. If the token &
jobId combination does not correspond to an actual job, then a
HTML-formatted error message is returned. If there is a
problem with the backend, the returned value can be ``ERROR``.
When status is ``COMPLETED``, you can retrieve the results of
the query via :func:`queryClient.results()`.
Example
-------
.. code-block:: python
import time
query = 'select ra,dec from gaia_dr3.gaia_source limit 200000'
jobId = queryClient.query(adql=query, fmt='csv', async_=True)
while True:
status = queryClient.status(jobId)
print ("time index =", time.localtime()[5], " status =", status)
if status == 'COMPLETED':
break
time.sleep(1)
This prints
.. code::
time index = 16 status = EXECUTING
time index = 17 status = EXECUTING
time index = 18 status = COMPLETED
'''
return qc_client._status (token=def_token(token), jobId=jobId,
profile=profile)
# --------------------------------------------------------------------
# JOBS -- Get a list of the user's Async jobs.
#
@multimethod('qc',2,False)
def jobs(token, jobId, format='text', status='all', option='list'):
return qc_client._jobs (token=def_token(token), jobId=jobId,
format=format, status=status, option=option)
@multimethod('qc',1,False)
def jobs(optval, jobId=None, format='text', status='all', option='list'):
if optval is not None and is_auth_token(optval):
# optval looks like a token
return qc_client._jobs (token=def_token(optval), jobId=jobId,
format=format, status=status, option=option)
else:
# optval is probably a jobId
return qc_client._jobs (token=def_token(None), jobId=optval,
format=format, status=status, option=option)
@multimethod('qc',0,False)
def jobs(token=None, jobId=None, format='text', status='all', option='list'):
'''Get a list of the user's Async jobs.
Usage::
jobs (token=None, jobId=None, format='text', status='all')
MultiMethod Usage::
queryClient.jobs (jobId)
queryClient.jobs (token, jobId)
queryClient.jobs (token, jobId=<id>)
queryClient.jobs (jobId=<str>)
Use the authentication token and the jobId of a previously issued
Asynchronous query to check the query's current status.
Parameters
----------
token : str [Optional]
Authentication token (see function :func:`authClient.login()`).
jobId : str
The jobId returned when issuing an Asynchronous query via
:func:`queryClient.query()` with ``async_=True``.
format : str
Format of the result. Support values include 'text' for a simple
formatted table suitable for printing, or 'json' for a JSON
string of the full matching record(s).
status : str
If ``status='all'`` then all Async jobs are returned, otherwise this
value may be used to return only those jobs with the specified
status. Allowed values are:
* 'all' Return all jobs.
* 'EXECUTING' Job is still running.
* 'COMPLETED' Job completed successfully.
* 'ERROR' Job exited with an error.
* 'ABORTED' Job was aborted by the user.
option : str
If ``list`` then the matching records are returned, if ``delete`` then
the records are removed from the database (e.g. to clear up long
job lists of completed jobs).
Returns
-------
joblist : str
Returns a list of Async query jobs submitted by the user in the
last 30 days, possibly filtered by the ``status`` parameter. The
'json' format option allows the caller to format the full contents
of the job record beyond the supplied simple 'text' option.
Example
-------
.. code-block:: python
print (queryClient.jobs(jobId))
This prints
.. code::
JobID Start End Status
tfu8zpn2tkrlfyr9e 07-22-20T13:10:22 07-22-20T13:34:12 COMPLETED
k8uznptrkkl29ryef 07-22-20T14:09:45 EXECUTING
: : : :
'''
return qc_client._jobs (token=def_token(token), jobId=jobId,
format=format, status=status, option=option)
# --------------------------------------------------------------------
# RESULTS -- Get the results of an Asynchronous query
#
@multimethod('qc',2,False)
def results(token, jobId, fname=None, delete=True, profile='default', progress=False):
return qc_client._results (token=def_token(token), jobId=jobId,
fname=fname, delete=True, profile=profile, progress=progress)
@multimethod('qc',1,False)
def results(optval, jobId=None, fname=None, delete=True, profile='default', progress=False):
if optval is not None and is_auth_token(optval):
# optval looks like a token
return qc_client._results (token=def_token(optval), jobId=jobId,
fname=fname, delete=delete, profile=profile, progress=progress)
else:
# optval is probably a jobId
return qc_client._results (token=def_token(None), jobId=optval,
fname=fname, delete=delete, profile=profile, progress=progress)
@multimethod('qc',0,False)
def results(token=None, jobId=None, fname=None, delete=True, profile='default', progress=False):
'''Retrieve the results of an Asynchronous query, once completed.
Usage::
results (token=None, jobId=None, delete=True)
MultiMethod Usage::
queryClient.results (jobId)
queryClient.results (token, jobId)
queryClient.results (token, jobId=<id>)
queryClient.results (jobId=<str>)
Parameters
----------
token : str [Optional]
Authentication token (see function :func:`authClient.login()`).
jobId : str
The jobId returned when issuing an Asynchronous query via
:func:`queryClient.query()` with ``async_=True``.
progress: bool
Set to ``False`` by default. If progress set to ``True`` it will
report the download progress.
Returns
-------
results : str
Example
-------
.. code-block:: python
# issue an Async query (here a tiny one just for this example)
query = 'select ra,dec from gaia_dr3.gaia_source limit 3'
jobId = queryClient.query(adql=query, fmt='csv', async_=True)
# ensure job completes...then check status and retrieve results
time.sleep(4)
if queryClient.status(jobId) == 'COMPLETED':
results = queryClient.results(jobId)
print (type(results))
print (results)
This prints
.. code::
<type 'str'>
ra,dec
314.14738713961134,37.33643208345386
314.1588238386895,37.33682543157976
314.1519366421579,37.33533842266872
'''
return qc_client._results (token=def_token(token), jobId=jobId,
fname=fname, delete=True, profile=profile, progress=progress)
# --------------------------------------------------------------------
# ERROR -- Get the error message of a failed Asynchronous query
#
@multimethod('qc',2,False)
def error(token, jobId, profile='default'):
return qc_client._error (token=def_token(token), jobId=jobId,
profile=profile)
@multimethod('qc',1,False)
def error(optval, jobId=None, profile='default'):
if optval is not None and is_auth_token(optval):
# optval looks like a token
return qc_client._error (token=def_token(optval), jobId=jobId,
profile=profile)
else:
# optval is probably a jobId
return qc_client._error (token=def_token(None), jobId=optval,
profile=profile)
@multimethod('qc',0,False)
def error(token=None, jobId=None, profile='default'):
'''Retrieve the error of an Asynchronous query, once completed.
Usage::
error (token=None, jobId=None)
MultiMethod Usage::
queryClient.error (jobId)
queryClient.error (token, jobId)
queryClient.error (token, jobId=<id>)
queryClient.error (jobId=<str>)
Parameters
----------
token : str [Optional]
Authentication token (see function :func:`authClient.login()`).
jobId : str
The jobId returned when issuing an Asynchronous query via
:func:`queryClient.query()` with ``async_=True``.
Returns
-------
error : str
Example
-------
.. code-block:: python
# issue an Async query (here a tiny one just for this example)
query = 'select ra,dec1 from gaia_dr3.gaia_source limit 3'
jobId = queryClient.query(adql=query, fmt='csv', async_=True)
# ensure job completes...then check status and retrieve error
time.sleep(4)
if queryClient.status(jobId) == 'ERROR':
error = queryClient.error(jobId)
print (type(error))
print (error)
This prints
.. code::
<class 'str'>
Error: IllegalArgumentException: Column [dec1] does not exist.
'''
return qc_client._error (token=def_token(token), jobId=jobId,
profile=profile)
# --------------------------------------------------------------------
# ABORT -- Abort the specified Asynchronous job.
#
@multimethod('qc',2,False)
def abort(token, jobId, profile='default'):
return qc_client._abort (token=def_token(token), jobId=jobId,
profile=profile)
@multimethod('qc',1,False)
def abort(optval, jobId=None, profile='default'):
if optval is not None and is_auth_token(optval):
# optval looks like a token
return qc_client._abort (token=def_token(optval), jobId=jobId,
profile=profile)
else:
# optval is probably a jobId
return qc_client._abort (token=def_token(None), jobId=optval,
profile=profile)
@multimethod('qc',0,False)
def abort(token=None, jobId=None, profile='default'):
'''Abort the specified Asynchronous job.
Usage::
abort (token=None, jobId=None)
MultiMethod Usage::
queryClient.abort (token, jobId)
queryClient.abort (jobId)
queryClient.abort (token, jobId=<id>)
queryClient.abort (jobId=<str>)
Parameters
----------
token : str [Optional]