a
    !f                     @   s  d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 ddlmZ dd	lmZ dd
lmZ ddlmZ G dd deZdd ZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG d d! d!eZG d"d# d#eZG d$d% d%eZG d&d' d'eZG d(d) d)eZG d*d+ d+eZ G d,d- d-eZ!G d.d/ d/eZ"G d0d1 d1eZ#G d2d3 d3eZ$dS )4zDefine API Jobs.    N)NotFound)_datetime_from_microseconds)Dataset)SchemaField)Table)_build_schema_resource)_parse_schema_resource)_EnumProperty)_TypedPropertyc                   @   s    e Zd ZdZdd Zdd ZdS )UDFResourcea4  Describe a single user-defined function (UDF) resource.
    :type udf_type: str
    :param udf_type: the type of the resource ('inlineCode' or 'resourceUri')

    :type value: str
    :param value: the inline code or resource URI

    See
    https://cloud.google.com/bigquery/user-defined-functions#api
    c                 C   s   || _ || _d S Nudf_typevalue)selfr   r    r   T/var/www/html/python-backend/venv/lib/python3.9/site-packages/gcloud/bigquery/job.py__init__)   s    zUDFResource.__init__c                 C   s   | j |j ko| j|jkS r   r   )r   otherr   r   r   __eq__-   s    
zUDFResource.__eq__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r      s   
r   c                 C   s(   g }| D ]}|j |ji}|| q|S )z
    :type resources: sequence of :class:`UDFResource`
    :param resources: fields to be appended

    :rtype: mapping
    :returns: a mapping describing userDefinedFunctionResources for the query.
    )r   r   append)	resourcesZudfsresourceZudfr   r   r   _build_udf_resources3   s
    r   c                   @   s    e Zd ZdZdd Zdd ZdS )UDFResourcesPropertyziCustom property type for :class:`QueryJob`.

    Also used by :class:`~gcloud.bigquery.query.Query`.
    c                 C   s   |du r| S t |jS )zDescriptor protocal:  accesstorN)list_udf_resources)r   instanceownerr   r   r   __get__G   s    zUDFResourcesProperty.__get__c                 C   s(   t dd |D stdt||_dS )zDescriptor protocal:  mutatorc                 s   s   | ]}t |tV  qd S r   )
isinstancer   ).0ur   r   r   	<genexpr>O       z/UDFResourcesProperty.__set__.<locals>.<genexpr>zudf items must be UDFResourceN)all
ValueErrortupler    )r   r!   r   r   r   r   __set__M   s    zUDFResourcesProperty.__set__N)r   r   r   r   r#   r,   r   r   r   r   r   B   s   r   c                   @   s    e Zd ZdZdZdZeefZdS )Compressionz+Pseudo-enum for ``compression`` properties.GZIPNONEN)r   r   r   r   r.   r/   ALLOWEDr   r   r   r   r-   T   s   r-   c                   @   s    e Zd ZdZdZdZeefZdS )CreateDispositionz2Pseudo-enum for ``create_disposition`` properties.CREATE_IF_NEEDEDCREATE_NEVERN)r   r   r   r   r2   r3   r0   r   r   r   r   r1   [   s   r1   c                   @   s&   e Zd ZdZdZdZdZeeefZdS )DestinationFormatz2Pseudo-enum for ``destination_format`` properties.CSVNEWLINE_DELIMITED_JSONAVRON)r   r   r   r   r5   r6   r7   r0   r   r   r   r   r4   b   s
   r4   c                   @   s    e Zd ZdZdZdZeefZdS )Encodingz(Pseudo-enum for ``encoding`` properties.zUTF-8z
ISO-8559-1N)r   r   r   r   ZUTF_8Z
ISO_8559_1r0   r   r   r   r   r8   j   s   r8   c                   @   s    e Zd ZdZdZdZeefZdS )QueryPriorityz/Pseudo-enum for ``QueryJob.priority`` property.INTERACTIVEBATCHN)r   r   r   r   r:   r;   r0   r   r   r   r   r9   q   s   r9   c                   @   s&   e Zd ZdZdZdZdZeeefZdS )SourceFormatz-Pseudo-enum for ``source_format`` properties.r5   DATASTORE_BACKUPr6   N)r   r   r   r   r5   r=   r6   r0   r   r   r   r   r<   x   s
   r<   c                   @   s&   e Zd ZdZdZdZdZeeefZdS )WriteDispositionz1Pseudo-enum for ``write_disposition`` properties.WRITE_APPENDWRITE_TRUNCATEWRITE_EMPTYN)r   r   r   r   r?   r@   rA   r0   r   r   r   r   r>      s
   r>   c                   @   s,   e Zd ZdZdd Zedd Zdd ZdS )	_BaseJobzBase class for jobs.

    :type client: :class:`gcloud.bigquery.client.Client`
    :param client: A client which holds credentials and project configuration
                   for the dataset (which requires a project).
    c                 C   s   || _ i | _d S r   )_client_propertiesr   clientr   r   r   r      s    z_BaseJob.__init__c                 C   s   | j jS )zsProject bound to the job.

        :rtype: string
        :returns: the project (derived from the client).
        )rC   projectr   r   r   r   rG      s    z_BaseJob.projectc                 C   s   |du r| j }|S )a  Check client or verify over-ride.

        :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current dataset.

        :rtype: :class:`gcloud.bigquery.client.Client`
        :returns: The client passed in or the currently bound client.
        N)rC   rE   r   r   r   _require_client   s    
z_BaseJob._require_clientN)r   r   r   r   r   propertyrG   rI   r   r   r   r   rB      s
   
rB   c                       s   e Zd ZdZ fddZedd Zedd Zedd	 Zed
d Z	edd Z
edd Zedd Zedd Zedd Zedd Zedd Zdd Zdd Zedd Zd)d!d"Zd*d#d$Zd+d%d&Zd,d'd(Z  ZS )-	_AsyncJoba*  Base class for asynchronous jobs.

    :type name: string
    :param name: the name of the job

    :type client: :class:`gcloud.bigquery.client.Client`
    :param client: A client which holds credentials and project configuration
                   for the dataset (which requires a project).
    c                    s   t t| | || _d S r   )superrK   r   name)r   rM   rF   	__class__r   r   r      s    z_AsyncJob.__init__c                 C   s   | j S )zhType of job

        :rtype: string
        :returns: one of 'load', 'copy', 'extract', 'query'
        )	_JOB_TYPErH   r   r   r   job_type   s    z_AsyncJob.job_typec                 C   s   d| j | jf S )zwURL path for the job's APIs.

        :rtype: string
        :returns: the path based on project and job name.
        z/projects/%s/jobs/%s)rG   rM   rH   r   r   r   path   s    z_AsyncJob.pathc                 C   s   | j dS )zETag for the job resource.

        :rtype: string, or ``NoneType``
        :returns: the ETag (None until set from the server).
        etagrD   getrH   r   r   r   rS      s    z_AsyncJob.etagc                 C   s   | j dS )zURL for the job resource.

        :rtype: string, or ``NoneType``
        :returns: the URL (None until set from the server).
        ZselfLinkrT   rH   r   r   r   	self_link   s    z_AsyncJob.self_linkc                 C   s   | j dS )zE-mail address of user who submitted the job.

        :rtype: string, or ``NoneType``
        :returns: the URL (None until set from the server).
        
user_emailrT   rH   r   r   r   rW      s    z_AsyncJob.user_emailc                 C   s6   | j d}|dur2|d}|dur2t|d S dS )zDatetime at which the job was created.

        :rtype: ``datetime.datetime``, or ``NoneType``
        :returns: the creation time (None until set from the server).
        
statisticsNcreationTime     @@rD   rU   r   r   rX   Zmillisr   r   r   created   s
    
z_AsyncJob.createdc                 C   s6   | j d}|dur2|d}|dur2t|d S dS )zDatetime at which the job was started.

        :rtype: ``datetime.datetime``, or ``NoneType``
        :returns: the start time (None until set from the server).
        rX   N	startTimerZ   r[   r\   r   r   r   started   s
    
z_AsyncJob.startedc                 C   s6   | j d}|dur2|d}|dur2t|d S dS )zDatetime at which the job finished.

        :rtype: ``datetime.datetime``, or ``NoneType``
        :returns: the end time (None until set from the server).
        rX   NendTimerZ   r[   r\   r   r   r   ended   s
    
z_AsyncJob.endedc                 C   s"   | j d}|dur|dS dS )zError information about the job as a whole.

        :rtype: mapping, or ``NoneType``
        :returns: the error information (None until set from the server).
        statusNZerrorResultrT   r   rb   r   r   r   error_result  s    z_AsyncJob.error_resultc                 C   s"   | j d}|dur|dS dS )zInformation about individual errors generated by the job.

        :rtype: list of mappings, or ``NoneType``
        :returns: the error information (None until set from the server).
        rb   NerrorsrT   rc   r   r   r   re     s    z_AsyncJob.errorsc                 C   s"   | j d}|dur|dS dS )zStatus of the job.

        :rtype: string, or ``NoneType``
        :returns: the state (None until set from the server).
        rb   NstaterT   rc   r   r   r   rf   #  s    z_AsyncJob.statec                 C   s   dS )/Helper:  handle subclass properties in cleaned.Nr   )r   cleanedr   r   r   _scrub_local_properties.  s    z!_AsyncJob._scrub_local_propertiesc                 C   s   |  }| | |di }d|v r6t|d |d< d|v rNt|d |d< d|v rft|d |d< | j  | j| dS )zUpdate properties from resource in body of ``api_response``

        :type api_response: httplib2.Response
        :param api_response: response returned from an API call
        rX   rY   r^   r`   N)copyri   rU   floatrD   clearupdate)r   api_responserh   rX   r   r   r   _set_properties2  s    

z_AsyncJob._set_propertiesc                 C   sb   d|vsd|d vrt d|d d }d|vs>| j|d vrLt d| j |d | j }||fS )a  Helper for :meth:`from_api_repr`

        :type resource: dict
        :param resource: resource for the job

        :rtype: dict
        :returns: tuple (string, dict), where the first element is the
                  job name and the second contains job-specific configuration.
        :raises: :class:`KeyError` if the resource has no identifier, or
                 is missing the appropriate configuration.
        jobReferencejobIdzGResource lacks required identity information: ["jobReference"]["jobId"]configurationz>Resource lacks required configuration: ["configuration"]["%s"])KeyErrorrP   )clsr   rM   configr   r   r   _get_resource_configF  s    
z_AsyncJob._get_resource_configNc                 C   s:   |  |}d| jf }|jjd||  d}| | dS )ae  API call:  begin the job via a POST request

        See:
        https://cloud.google.com/bigquery/docs/reference/v2/jobs/insert

        :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current dataset.
        z/projects/%s/jobsPOST)methodrR   dataN)rI   rG   
connectionapi_request_build_resourcero   )r   rF   rR   rn   r   r   r   begin_  s    


z_AsyncJob.beginc                 C   sD   |  |}z|jjd| jddid W n ty:   Y dS 0 dS dS )a  API call:  test for the existence of the job via a GET request

        See
        https://cloud.google.com/bigquery/docs/reference/v2/jobs/get

        :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current dataset.

        :rtype: bool
        :returns: Boolean indicating existence of the job.
        GETfieldsid)rx   rR   Zquery_paramsFTN)rI   rz   r{   rR   r   rE   r   r   r   existso  s    

z_AsyncJob.existsc                 C   s*   |  |}|jjd| jd}| | dS )ai  API call:  refresh job properties via a GET request

        See
        https://cloud.google.com/bigquery/docs/reference/v2/jobs/get

        :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current dataset.
        r~   rx   rR   NrI   rz   r{   rR   ro   r   rF   rn   r   r   r   reload  s
    

z_AsyncJob.reloadc                 C   s0   |  |}|jjdd| jf d}| | dS )aa  API call:  cancel job via a POST request

        See
        https://cloud.google.com/bigquery/docs/reference/v2/jobs/cancel

        :type client: :class:`gcloud.bigquery.client.Client` or ``NoneType``
        :param client: the client to use.  If not passed, falls back to the
                       ``client`` stored on the current dataset.
        rw   z	%s/cancelr   Nr   r   r   r   r   cancel  s
    

z_AsyncJob.cancel)N)N)N)N)r   r   r   r   r   rJ   rQ   rR   rS   rV   rW   r]   r_   ra   rd   re   rf   ri   ro   classmethodrv   r}   r   r   r   __classcell__r   r   rN   r   rK      s@   	

















rK   c                   @   s<   e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdS )_LoadConfigurationzjUser-settable configuration options for load jobs.

    Values which are ``None`` -> server defaults.
    N)r   r   r   r   Z_allow_jagged_rowsZ_allow_quoted_newlines_create_disposition	_encoding_field_delimiterZ_ignore_unknown_valuesZ_max_bad_recordsZ_quote_characterZ_skip_leading_rowsZ_source_format_write_dispositionr   r   r   r   r     s   r   c                       s  e Zd ZdZdZdZd% fdd	Zedd Zej	d	d Zed
d Z
edd Zedd Zedd ZedeZedeZedZedZedejZedeZedejZedejZedejZedZe dZ!dd Z"dd  Z#d!d" Z$e%d#d$ Z&  Z'S )&LoadTableFromStorageJoba  Asynchronous job for loading data into a table from CloudStorage.

    :type name: string
    :param name: the name of the job

    :type destination: :class:`gcloud.bigquery.table.Table`
    :param destination: Table into which data is to be loaded.

    :type source_uris: sequence of string
    :param source_uris: URIs of one or more data files to be loaded, in
                        format ``gs://<bucket_name>/<object_name_or_glob>``.

    :type client: :class:`gcloud.bigquery.client.Client`
    :param client: A client which holds credentials and project configuration
                   for the dataset (which requires a project).

    :type schema: list of :class:`gcloud.bigquery.table.SchemaField`
    :param schema: The job's schema
    Nloadr   c                    s0   t t| || || _|| _|| _t | _d S r   )rL   r   r   destinationsource_urisschemar   _configuration)r   rM   r   r   rF   r   rN   r   r   r     s
    z LoadTableFromStorageJob.__init__c                 C   s
   t | jS )zuTable's schema.

        :rtype: list of :class:`SchemaField`
        :returns: fields describing the schema
        )r   _schemarH   r   r   r   r     s    zLoadTableFromStorageJob.schemac                 C   s(   t dd |D stdt|| _dS )a  Update table's schema

        :type value: list of :class:`SchemaField`
        :param value: fields describing the schema

        :raises: TypeError if 'value' is not a sequence, or ValueError if
                 any item in the sequence is not a SchemaField
        c                 s   s   | ]}t |tV  qd S r   )r$   r   )r%   fieldr   r   r   r'     r(   z1LoadTableFromStorageJob.schema.<locals>.<genexpr>zSchema items must be fieldsN)r)   r*   r+   r   )r   r   r   r   r   r     s    
c                 C   s(   | j d}|dur$t|d d S dS )zCount of bytes loaded from source files.

        :rtype: integer, or ``NoneType``
        :returns: the count (None until set from the server).
        rX   Nr   ZinputFileBytesrD   rU   intr   rX   r   r   r   input_file_bytes  s    z(LoadTableFromStorageJob.input_file_bytesc                 C   s(   | j d}|dur$t|d d S dS )zCount of source files.

        :rtype: integer, or ``NoneType``
        :returns: the count (None until set from the server).
        rX   Nr   Z
inputFilesr   r   r   r   r   input_files  s    z#LoadTableFromStorageJob.input_filesc                 C   s(   | j d}|dur$t|d d S dS )zCount of bytes saved to destination table.

        :rtype: integer, or ``NoneType``
        :returns: the count (None until set from the server).
        rX   Nr   ZoutputBytesr   r   r   r   r   output_bytes  s    z$LoadTableFromStorageJob.output_bytesc                 C   s(   | j d}|dur$t|d d S dS )zCount of rows saved to destination table.

        :rtype: integer, or ``NoneType``
        :returns: the count (None until set from the server).
        rX   Nr   Z
outputRowsr   r   r   r   r   output_rows  s    z#LoadTableFromStorageJob.output_rowsallow_jagged_rowsallow_quoted_newlinescreate_dispositionencodingfield_delimiterignore_unknown_valuesmax_bad_recordsquote_characterskip_leading_rowssource_formatwrite_dispositionc                 C   s   | j dur| j |d< | jdur(| j|d< | jdur<| j|d< | jdurP| j|d< | jdurd| j|d< | jdurx| j|d< | jdur| j|d< | jdur| j|d	< | jdur| j|d
< | j	dur| j	|d< | j
dur| j
|d< dS )>Helper for _build_resource: copy config properties to resourceNZallowJaggedRowsZallowQuotedNewlinescreateDispositionr   fieldDelimiterZignoreUnknownValuesZmaxBadRecordsquoteZskipLeadingRowsZsourceFormatwriteDisposition)r   r   r   r   r   r   r   r   r   r   r   r   rr   r   r   r   _populate_config_resourceS  s,    




















z1LoadTableFromStorageJob._populate_config_resourcec                 C   sr   | j | jd| j| j| jj | jj| jjddid}|d | j }| | t| jdkrndt	| ji|d< |S )	&Generate a resource for :meth:`begin`.	projectIdrq   r   	datasetIdtableId)
sourceUrisdestinationTablerp   rr   rr   r   r   r   )
rG   rM   rP   r   r   dataset_namer   lenr   r   r   r   rr   r   r   r   r|   l  s$    

z'LoadTableFromStorageJob._build_resourcec                 C   s   | dddi}t|| _dS )rg   r   r   r   N)popr   r   )r   rh   r   r   r   r   ri     s    z/LoadTableFromStorageJob._scrub_local_propertiesc           
      C   s\   |  |\}}|d }t|d |}t|d |}|dd}| ||||d}	|	| |	S )aU  Factory:  construct a job given its API representation

        .. note:

           This method assumes that the project found in the resource matches
           the client's project.

        :type resource: dict
        :param resource: dataset job representation returned from the API

        :type client: :class:`gcloud.bigquery.client.Client`
        :param client: Client which holds credentials and project
                       configuration for the dataset.

        :rtype: :class:`gcloud.bigquery.job.LoadTableFromStorageJob`
        :returns: Job parsed from ``resource``.
        r   r   r   r   r   rF   )rv   r   r   rU   ro   )
rt   r   rF   rM   ru   dest_configdatasetr   Zsource_urlsjobr   r   r   from_api_repr  s    
z%LoadTableFromStorageJob.from_api_repr)r   )(r   r   r   r   r   rP   r   rJ   r   setterr   r   r   r   r
   boolr   r   r1   r   r8   r   sixstring_typesr   r   integer_typesr   r   r   r<   r   r>   r   r   r|   ri   r   r   r   r   r   rN   r   r     s@   












r   c                   @   s   e Zd ZdZdZdZdS )_CopyConfigurationzjUser-settable configuration options for copy jobs.

    Values which are ``None`` -> server defaults.
    N)r   r   r   r   r   r   r   r   r   r   r     s   r   c                       sP   e Zd ZdZdZ fddZedZedZ	dd Z
d	d
 Zedd Z  ZS )CopyJoba<  Asynchronous job: copy data into a table from other tables.

    :type name: string
    :param name: the name of the job

    :type destination: :class:`gcloud.bigquery.table.Table`
    :param destination: Table into which data is to be loaded.

    :type sources: list of :class:`gcloud.bigquery.table.Table`
    :param sources: Table into which data is to be loaded.

    :type client: :class:`gcloud.bigquery.client.Client`
    :param client: A client which holds credentials and project configuration
                   for the dataset (which requires a project).
    rj   c                    s*   t t| || || _|| _t | _d S r   )rL   r   r   r   sourcesr   r   )r   rM   r   r   rF   rN   r   r   r     s    zCopyJob.__init__r   r   c                 C   s,   | j dur| j |d< | jdur(| j|d< dS )r   Nr   r   )r   r   r   r   r   r   r     s    


z!CopyJob._populate_config_resourcec                 C   s`   dd | j D }| j| jd| j|| jj| jj| jjddid}|d | j }| | |S )r   c                 S   s   g | ]}|j |j|jd qS )r   )rG   r   rM   )r%   tabler   r   r   
<listcomp>  s
   z+CopyJob._build_resource.<locals>.<listcomp>r   r   )sourceTablesr   r   rr   )r   rG   rM   rP   r   r   r   )r   Zsource_refsr   rr   r   r   r   r|     s$    
zCopyJob._build_resourcec                 C   s   |  |\}}|d }t|d |}t|d |}g }|d D ]&}	t|	d |}|t|	d | q>| ||||d}
|
| |
S )aE  Factory:  construct a job given its API representation

        .. note:

           This method assumes that the project found in the resource matches
           the client's project.

        :type resource: dict
        :param resource: dataset job representation returned from the API

        :type client: :class:`gcloud.bigquery.client.Client`
        :param client: Client which holds credentials and project
                       configuration for the dataset.

        :rtype: :class:`gcloud.bigquery.job.CopyJob`
        :returns: Job parsed from ``resource``.
        r   r   r   r   r   )rv   r   r   r   ro   )rt   r   rF   rM   ru   r   r   r   r   source_configr   r   r   r   r     s    
zCopyJob.from_api_repr)r   r   r   r   rP   r   r1   r   r>   r   r   r|   r   r   r   r   r   rN   r   r     s   r   c                   @   s    e Zd ZdZdZdZdZdZdS )_ExtractConfigurationzmUser-settable configuration options for extract jobs.

    Values which are ``None`` -> server defaults.
    N)r   r   r   r   _compressionZ_destination_formatr   Z_print_headerr   r   r   r   r     s
   r   c                       sf   e Zd ZdZdZ fddZedZedZ	e
dejZe
deZd	d
 Zdd Zedd Z  ZS )ExtractTableToStorageJoba  Asynchronous job: extract data from a table into Cloud Storage.

    :type name: string
    :param name: the name of the job

    :type source: :class:`gcloud.bigquery.table.Table`
    :param source: Table into which data is to be loaded.

    :type destination_uris: list of string
    :param destination_uris: URIs describing Cloud Storage blobs into which
                             extracted data will be written, in format
                             ``gs://<bucket_name>/<object_name_or_glob>``.

    :type client: :class:`gcloud.bigquery.client.Client`
    :param client: A client which holds credentials and project configuration
                   for the dataset (which requires a project).
    extractc                    s*   t t| || || _|| _t | _d S r   )rL   r   r   sourcedestination_urisr   r   )r   rM   r   r   rF   rN   r   r   r   9  s    z!ExtractTableToStorageJob.__init__compressiondestination_formatr   print_headerc                 C   sT   | j dur| j |d< | jdur(| j|d< | jdur<| j|d< | jdurP| j|d< dS )r   Nr   ZdestinationFormatr   ZprintHeader)r   r   r   r   r   r   r   r   r   S  s    






z2ExtractTableToStorageJob._populate_config_resourcec                 C   sV   | j j| j j| j jd}| j| jd| j|| jdid}|d | j }| | |S )r   r   r   )sourceTabledestinationUrisr   rr   )r   rG   r   rM   rP   r   r   )r   Z
source_refr   rr   r   r   r   r|   ^  s     
z(ExtractTableToStorageJob._build_resourcec           
      C   sX   |  |\}}|d }t|d |}t|d |}|d }| ||||d}	|	| |	S )aV  Factory:  construct a job given its API representation

        .. note:

           This method assumes that the project found in the resource matches
           the client's project.

        :type resource: dict
        :param resource: dataset job representation returned from the API

        :type client: :class:`gcloud.bigquery.client.Client`
        :param client: Client which holds credentials and project
                       configuration for the dataset.

        :rtype: :class:`gcloud.bigquery.job.ExtractTableToStorageJob`
        :returns: Job parsed from ``resource``.
        r   r   r   r   r   )rv   r   r   ro   )
rt   r   rF   rM   ru   r   r   r   r   r   r   r   r   r   x  s    
z&ExtractTableToStorageJob.from_api_repr)r   r   r   r   rP   r   r-   r   r4   r   r
   r   r   r   r   r   r   r|   r   r   r   r   r   rN   r   r   %  s   
r   c                   @   s4   e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdS )_AsyncQueryConfigurationzxUser-settable configuration options for asynchronous query jobs.

    Values which are ``None`` -> server defaults.
    N)r   r   r   r   Z_allow_large_resultsr   Z_default_datasetZ_destinationZ_flatten_resultsZ	_priorityZ_use_query_cacheZ_use_legacy_sqlr   r   r   r   r   r     s   r   c                       s   e Zd ZdZdZdZd fdd	ZedeZ	e
dZed	eZed
eZedeZedZe ZedeZedeZedZdd Zdd Zdd Zdd Zedd Z  ZS )QueryJoba  Asynchronous job: query tables.

    :type name: string
    :param name: the name of the job

    :type query: string
    :param query: SQL query string

    :type client: :class:`gcloud.bigquery.client.Client`
    :param client: A client which holds credentials and project configuration
                   for the dataset (which requires a project).

    :type udf_resources: tuple
    :param udf_resources: An iterable of
                        :class:`gcloud.bigquery.job.UDFResource`
                        (empty by default)
    queryZuserDefinedFunctionResourcesr   c                    s*   t t| || || _|| _t | _d S r   )rL   r   r   r   udf_resourcesr   r   )r   rM   r   rF   r   rN   r   r   r     s    zQueryJob.__init__allow_large_resultsr   default_datasetr   flatten_resultspriorityuse_query_cacheuse_legacy_sqlr   c                 C   s&   | j dur"| j j| j j| j jdS dS )zCreate a JSON resource for the destination table.

        Helper for :meth:`_populate_config_resource` and
        :meth:`_scrub_local_properties`
        Nr   )r   rG   r   rM   rH   r   r   r   _destination_table_resource  s
    
z$QueryJob._destination_table_resourcec                 C   s   | j dur| j |d< | jdur(| j|d< | jdurH| jj| jjd|d< | jdurb|  }||d< | jdurv| j|d< | jdur| j|d< | j	dur| j	|d	< | j
dur| j
|d
< | jdur| j|d< t| jdkrt| j|| j< dS )r   NZallowLargeResultsr   )r   r   ZdefaultDatasetr   ZflattenResultsr   ZuseQueryCacheZuseLegacySqlr   r   )r   r   r   rG   rM   r   r   r   r   r   r   r   r   r    r   _UDF_KEY)r   rr   Z	table_resr   r   r   r     s2    
















z"QueryJob._populate_config_resourcec                 C   s<   | j | jd| jd| jiid}|d | j }| | |S )r   r   r   r   rr   )rG   rM   rP   r   r   r   r   r   r   r|     s    
zQueryJob._build_resourcec                 C   sb   |d d }| d}|du r.| jdur^| `n0|  }||kr^| j|d }||d | _dS )zHelper:  handle subclass properties in cleaned.

        .. note:

           This method assumes that the project found in the resource matches
           the client's project.
        rr   r   r   Nr   r   )rU   r   r   rC   r   r   )r   rh   rr   Zdest_remoteZ
dest_localr   r   r   r   ri   ,  s    

z QueryJob._scrub_local_propertiesc                 C   s2   |  |\}}|d }| |||d}|| |S )a  Factory:  construct a job given its API representation

        :type resource: dict
        :param resource: dataset job representation returned from the API

        :type client: :class:`gcloud.bigquery.client.Client`
        :param client: Client which holds credentials and project
                       configuration for the dataset.

        :rtype: :class:`gcloud.bigquery.job.RunAsyncQueryJob`
        :returns: Job parsed from ``resource``.
        r   r   )rv   ro   )rt   r   rF   rM   ru   r   r   r   r   r   r   @  s
    
zQueryJob.from_api_repr)r   ) r   r   r   r   rP   r   r   r
   r   r   r1   r   r   r   r   r   r   r9   r   r   r   r   r   r>   r   r   r   r|   ri   r   r   r   r   r   rN   r   r     s(   





r   )%r   r   Zgcloud.exceptionsr   Zgcloud._helpersr   Zgcloud.bigquery.datasetr   Zgcloud.bigquery.tabler   r   r   r   Zgcloud.bigquery._helpersr	   r
   objectr   r   r   r-   r1   r4   r8   r9   r<   r>   rB   rK   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s@   # } q	hp