a
    !fQ                     @   sT   d Z ddlZddlmZ ddlmZ ddlmZ G dd deZ	G dd	 d	eZ
dS )
zDefine API Datasets.    N)_datetime_from_microseconds)NotFoundTablec                   @   s4   e Zd ZdZeg dZdd Zdd Zdd Zd	S )
AccessGranta]  Represent grant of an access role to an entity.

    Every entry in the access list will have exactly one of
    ``userByEmail``, ``groupByEmail``, ``domain``, ``specialGroup`` or
    ``view`` set. And if anything but ``view`` is set, it'll also have a
    ``role`` specified. ``role`` is omitted for a ``view``, since
    ``view`` s are always read-only.

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

    :type role: string
    :param role: Role granted to the entity. One of

                 * ``'OWNER'``
                 * ``'WRITER'``
                 * ``'READER'``

                 May also be ``None`` if the ``entity_type`` is ``view``.

    :type entity_type: string
    :param entity_type: Type of entity being granted the role. One of
                        :attr:`ENTITY_TYPES`.

    :type entity_id: string
    :param entity_id: ID of entity being granted the role.

    :raises: :class:`ValueError` if the ``entity_type`` is not among
             :attr:`ENTITY_TYPES`, or if a ``view`` has ``role`` set or
             a non ``view`` **does not** have a ``role`` set.
    )ZuserByEmailZgroupByEmaildomainZspecialGroupviewc                 C   sr   || j vr&d|d| j f }t||dkrF|d ur\td|f n|d u r\td|f || _|| _|| _d S )NzEntity type %r not among: %sz, r   z/Role must be None for a view. Received role: %rz#Role must be set for entity type %r)ENTITY_TYPESjoin
ValueErrorroleentity_type	entity_id)selfr   r   r   message r   X/var/www/html/python-backend/venv/lib/python3.9/site-packages/gcloud/bigquery/dataset.py__init__;   s"    
zAccessGrant.__init__c                 C   s$   | j |j ko"| j|jko"| j|jkS Nr   r   r   )r   otherr   r   r   __eq__M   s
    

zAccessGrant.__eq__c                 C   s   d| j | j| jf S )Nz<AccessGrant: role=%s, %s=%s>r   r   r   r   r   __repr__S   s    zAccessGrant.__repr__N)	__name__
__module____qualname____doc__	frozensetr	   r   r   r   r   r   r   r   r      s
   r   c                   @   s|  e Zd ZdZdZd?ddZedd Ze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d Zedd Zej
dd Zedd Zej
dd Zedd Zej
dd Zed d! Zej
d"d! Zed#d$ Zd%d& Zed'd( Zd)d* Zd+d, Zd-d. Zd@d/d0ZdAd1d2ZdBd3d4ZdCd5d6ZdDd7d8Z dEd9d:Z!dFd;d<Z"dGd=d>Z#dS )HDataseta  Datasets are containers for tables.

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

    :type name: string
    :param name: the name of the dataset

    :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 access_grants: list of :class:`AccessGrant`
    :param access_grants: roles granted to entities for this dataset
    Nr   c                 C   s   || _ || _i | _|| _d S r   )name_client_propertiesaccess_grants)r   r    clientr#   r   r   r   r   k   s    zDataset.__init__c                 C   s   | j jS )zwProject bound to the dataset.

        :rtype: string
        :returns: the project (derived from the client).
        )r!   projectr   r   r   r   r%   r   s    zDataset.projectc                 C   s   d| j | jf S )zURL path for the dataset's APIs.

        :rtype: string
        :returns: the path based on project and dataste name.
        z/projects/%s/datasets/%s)r%   r    r   r   r   r   path{   s    zDataset.pathc                 C   s
   t | jS )zDataset's access grants.

        :rtype: list of :class:`AccessGrant`
        :returns: roles granted to entities for this dataset
        )list_access_grantsr   r   r   r   r#      s    zDataset.access_grantsc                 C   s(   t dd |D stdt|| _dS )a&  Update dataset's access grants

        :type value: list of :class:`AccessGrant`
        :param value: roles granted to entities for this dataset

        :raises: TypeError if 'value' is not a sequence, or ValueError if
                 any item in the sequence is not an AccessGrant
        c                 s   s   | ]}t |tV  qd S r   )
isinstancer   ).0fieldr   r   r   	<genexpr>       z(Dataset.access_grants.<locals>.<genexpr>z$Values must be AccessGrant instancesN)allr   tupler(   r   valuer   r   r   r#      s    
c                 C   s$   | j d}|dur td| S dS )zDatetime at which the dataset was created.

        :rtype: ``datetime.datetime``, or ``NoneType``
        :returns: the creation time (None until set from the server).
        creationTimeN     @@r"   getr   )r   Zcreation_timer   r   r   created   s    zDataset.createdc                 C   s   | j dS )zID for the dataset resource.

        :rtype: string, or ``NoneType``
        :returns: the ID (None until set from the server).
        idr"   r5   r   r   r   r   
dataset_id   s    zDataset.dataset_idc                 C   s   | j dS )zETag for the dataset resource.

        :rtype: string, or ``NoneType``
        :returns: the ETag (None until set from the server).
        etagr8   r   r   r   r   r:      s    zDataset.etagc                 C   s$   | j d}|dur td| S dS )zDatetime at which the dataset was last modified.

        :rtype: ``datetime.datetime``, or ``NoneType``
        :returns: the modification time (None until set from the server).
        lastModifiedTimeNr3   r4   )r   Zmodified_timer   r   r   modified   s    zDataset.modifiedc                 C   s   | j dS )zURL for the dataset resource.

        :rtype: string, or ``NoneType``
        :returns: the URL (None until set from the server).
        ZselfLinkr8   r   r   r   r   	self_link   s    zDataset.self_linkc                 C   s   | j dS )zDefault expiration time for tables in the dataset.

        :rtype: integer, or ``NoneType``
        :returns: The time in milliseconds, or None (the default).
        defaultTableExpirationMsr8   r   r   r   r   default_table_expiration_ms   s    z#Dataset.default_table_expiration_msc                 C   s*   t |tjs|durtd|| jd< dS )zUpdate default expiration time for tables in the dataset.

        :type value: integer, or ``NoneType``
        :param value: new default time, in milliseconds

        :raises: ValueError for invalid value types.
        NPass an integer, or Noner>   )r)   sixinteger_typesr   r"   r0   r   r   r   r?      s    	c                 C   s   | j dS )zDescription of the dataset.

        :rtype: string, or ``NoneType``
        :returns: The description as set by the user, or None (the default).
        descriptionr8   r   r   r   r   rC      s    zDataset.descriptionc                 C   s*   t |tjs|durtd|| jd< dS )zUpdate description of the dataset.

        :type value: string, or ``NoneType``
        :param value: new description

        :raises: ValueError for invalid value types.
        NPass a string, or NonerC   r)   rA   string_typesr   r"   r0   r   r   r   rC      s    	c                 C   s   | j dS )zTitle of the dataset.

        :rtype: string, or ``NoneType``
        :returns: The name as set by the user, or None (the default).
        friendlyNamer8   r   r   r   r   friendly_name   s    zDataset.friendly_namec                 C   s*   t |tjs|durtd|| jd< dS )zUpdate title of the dataset.

        :type value: string, or ``NoneType``
        :param value: new title

        :raises: ValueError for invalid value types.
        NrD   rG   rE   r0   r   r   r   rH     s    	c                 C   s   | j dS )zLocation in which the dataset is hosted.

        :rtype: string, or ``NoneType``
        :returns: The location as set by the user, or None (the default).
        locationr8   r   r   r   r   rI     s    zDataset.locationc                 C   s*   t |tjs|durtd|| jd< dS )zUpdate location in which the dataset is hosted.

        :type value: string, or ``NoneType``
        :param value: new location

        :raises: ValueError for invalid value types.
        NrD   rI   rE   r0   r   r   r   rI     s    	c                 C   sB   d|vsd|d vrt d|d d }| ||d}|| |S )a  Factory:  construct a dataset given its API representation

        :type resource: dict
        :param resource: dataset resource 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.dataset.Dataset`
        :returns: Dataset parsed from ``resource``.
        datasetReference	datasetIdzNResource lacks required identity information:["datasetReference"]["datasetId"])r$   )KeyError_set_properties)clsresourcer$   r    datasetr   r   r   from_api_repr&  s    

zDataset.from_api_reprc                 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)r!   r   r$   r   r   r   _require_client=  s    
zDataset._require_clientc                 C   sZ   g }| D ]L}|  }|dd}| \}}t|dkrBtd||t||| q|S )a  Parse a resource fragment into a set of access grants.

        ``role`` augments the entity type and present **unless** the entity
        type is ``view``.

        :type access: list of mappings
        :param access: each mapping represents a single access grant

        :rtype: list of :class:`AccessGrant`
        :returns: a list of parsed grants
        :raises: :class:`ValueError` if a grant in ``access`` has more keys
                 than ``role`` and one additional key.
        r   Nr   z$Grant has unexpected keys remaining.)copypoppopitemlenr   appendr   )accessresultgrantr   r   r   r   r   r   _parse_access_grantsK  s    

zDataset._parse_access_grantsc                 C   s   | j   | }|dd}| || _d|v rBt|d |d< d|v rZt|d |d< d|v rrt|d |d< | 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
        rY   r   r2   r;   r>   N)	r"   clearrT   rU   r\   r#   floatintupdate)r   api_responsecleanedrY   r   r   r   rM   e  s    
zDataset._set_propertiesc                 C   s>   g }| j D ].}|j|ji}|jdur.|j|d< || q
|S )z9Generate a resource fragment for dataset's access grants.Nr   )r#   r   r   r   rX   )r   rZ   r[   infor   r   r   _build_access_resourcex  s    


zDataset._build_access_resourcec                 C   s   d| j | jdi}| jdur*| j}||d< | jdur>| j|d< | jdurR| j|d< | jdurf| j|d< t| jdkr|  |d	< |S )
z1Generate a resource for ``create`` or ``update``.rJ   )Z	projectIdrK   Nr>   rC   rG   rI   r   rY   )	r%   r    r?   rC   rH   rI   rW   r#   rd   )r   rO   r1   r   r   r   _build_resource  s     






zDataset._build_resourcec                 C   s:   |  |}d| jf }|jjd||  d}| | dS )ak  API call:  create the dataset via a PUT request

        See:
        https://cloud.google.com/bigquery/docs/reference/v2/tables/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/datasetsPOSTmethodr&   dataN)rS   r%   
connectionapi_requestre   rM   )r   r$   r&   ra   r   r   r   create  s    


zDataset.createc                 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 dataset via a GET request

        See
        https://cloud.google.com/bigquery/docs/reference/v2/datasets/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 dataset.
        GETfieldsr7   rh   r&   Zquery_paramsFTN)rS   rj   rk   r&   r   rR   r   r   r   exists  s    

zDataset.existsc                 C   s*   |  |}|jjd| jd}| | dS )aq  API call:  refresh dataset properties via a GET request

        See
        https://cloud.google.com/bigquery/docs/reference/v2/datasets/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.
        rm   rh   r&   N)rS   rj   rk   r&   rM   r   r$   ra   r   r   r   reload  s
    

zDataset.reloadc                 K   s   |  |}i }d|v rB|d }t|tjs:|dur:td||d< d|v rV|d |d< d|v rj|d |d< d|v r~|d |d< |jjd	| j|d
}| | dS )a  API call:  update individual dataset properties via a PATCH request

        See
        https://cloud.google.com/bigquery/docs/reference/v2/datasets/patch

        :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.

        :type kw: ``dict``
        :param kw: properties to be patched.

        :raises: ValueError for invalid value types.
        r?   Nr@   r>   rC   rH   rG   rI   PATCHrg   )	rS   r)   rA   rB   r   rj   rk   r&   rM   )r   r$   kwpartialr1   ra   r   r   r   patch  s"    
zDataset.patchc                 C   s0   |  |}|jjd| j|  d}| | dS )as  API call:  update dataset properties via a PUT request

        See
        https://cloud.google.com/bigquery/docs/reference/v2/datasets/update

        :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.
        PUTrg   N)rS   rj   rk   r&   re   rM   rr   r   r   r   r`     s
    

zDataset.updatec                 C   s    |  |}|jjd| jd dS )an  API call:  delete the dataset via a DELETE request

        See:
        https://cloud.google.com/bigquery/docs/reference/v2/tables/delete

        :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.
        DELETErq   N)rS   rj   rk   r&   rR   r   r   r   delete  s    

zDataset.deletec                    st   i }|dur||d< |dur$||d< d j  jf } jj}|jd||d} fdd|d	d
D }||dfS )aW  List tables for the project associated with this client.

        See:
        https://cloud.google.com/bigquery/docs/reference/v2/tables/list

        :type max_results: int
        :param max_results: maximum number of tables to return, If not
                            passed, defaults to a value set by the API.

        :type page_token: string
        :param page_token: opaque marker for the next "page" of datasets. If
                           not passed, the API will return the first page of
                           datasets.

        :rtype: tuple, (list, str)
        :returns: list of :class:`gcloud.bigquery.table.Table`, plus a
                  "next page token" string:  if not ``None``, indicates that
                  more tables can be retrieved with another call (pass that
                  value as ``page_token``).
        NZ
maxResultsZ	pageTokenz/projects/%s/datasets/%s/tablesrm   ro   c                    s   g | ]}t | qS r   )r   rQ   )r*   rO   r   r   r   
<listcomp>4  s   z'Dataset.list_tables.<locals>.<listcomp>tablesr   ZnextPageToken)r%   r    r!   rj   rk   r5   )r   Zmax_resultsZ
page_tokenparamsr&   rj   respr|   r   r   r   list_tables  s    

zDataset.list_tablesc                 C   s   t || |dS )aJ  Construct a table bound to this dataset.

        :type name: string
        :param name: Name of the table.

        :type schema: list of :class:`gcloud.bigquery.table.SchemaField`
        :param schema: The table's schema

        :rtype: :class:`gcloud.bigquery.table.Table`
        :returns: a new ``Table`` instance
        )rP   schemar   )r   r    r   r   r   r   table8  s    zDataset.table)r   )N)N)N)N)N)N)NN)r   )$r   r   r   r   r(   r   propertyr%   r&   r#   setterr6   r9   r:   r<   r=   r?   rC   rH   rI   classmethodrQ   rS   staticmethodr\   rM   rd   re   rl   rp   rs   rw   r`   rz   r   r   r   r   r   r   r   X   sj   
























&


%r   )r   rA   Zgcloud._helpersr   Zgcloud.exceptionsr   Zgcloud.bigquery.tabler   objectr   r   r   r   r   r   <module>   s   A