a
    !fy<                     @   s   d 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 ddlmZ G dd deZdddZdS )z8User friendly container for Google Cloud Bigtable Table.    )	_to_bytes)bigtable_pb2)bigtable_table_admin_pb2)	table_pb2)_gc_rule_from_pbColumnFamily)	AppendRow)ConditionalRow)	DirectRow)PartialRowsDatac                   @   s~   e Zd ZdZdd Zedd ZdddZdd
dZdd Z	dd Z
dddZdd Zdd Zd ddZd!ddZdd ZdS )"Tablea  Representation of a Google Cloud Bigtable Table.

    .. note::

        We don't define any properties on a table other than the name.
        The only other fields are ``column_families`` and ``granularity``,
        The ``column_families`` are not stored locally and
        ``granularity`` is an enum with only one value.

    We can use a :class:`Table` to:

    * :meth:`create` the table
    * :meth:`rename` the table
    * :meth:`delete` the table
    * :meth:`list_column_families` in the table

    :type table_id: str
    :param table_id: The ID of the table.

    :type instance: :class:`Instance <.instance.Instance>`
    :param instance: The instance that owns the table.
    c                 C   s   || _ || _d S N)table_id	_instance)selfr   instance r   V/var/www/html/python-backend/venv/lib/python3.9/site-packages/gcloud/bigtable/table.py__init__8   s    zTable.__init__c                 C   s   | j jd | j S )aE  Table name used in requests.

        .. note::

          This property will not change if ``table_id`` does not, but the
          return value is not cached.

        The table name is of the form

            ``"projects/../instances/../tables/{table_id}"``

        :rtype: str
        :returns: The table name.
        z/tables/)r   namer   )r   r   r   r   r   <   s    z
Table.nameNc                 C   s   t || |dS )a	  Factory to create a column family associated with this table.

        :type column_family_id: str
        :param column_family_id: The ID of the column family. Must be of the
                                 form ``[_a-zA-Z0-9][-_.a-zA-Z0-9]*``.

        :type gc_rule: :class:`.GarbageCollectionRule`
        :param gc_rule: (Optional) The garbage collection settings for this
                        column family.

        :rtype: :class:`.ColumnFamily`
        :returns: A column family owned by this table.
        gc_ruler   )r   column_family_idr   r   r   r   column_familyN   s    zTable.column_familyFc                 C   sF   |r|durt d|r"t|| S |dur8t|| |dS t|| S dS )a-  Factory to create a row associated with this table.

        .. warning::

           At most one of ``filter_`` and ``append`` can be used in a
           :class:`Row`.

        :type row_key: bytes
        :param row_key: The key for the row being created.

        :type filter_: :class:`.RowFilter`
        :param filter_: (Optional) Filter to be used for conditional mutations.
                        See :class:`.DirectRow` for more details.

        :type append: bool
        :param append: (Optional) Flag to determine if the row should be used
                       for append mutations.

        :rtype: :class:`.DirectRow`
        :returns: A row owned by this table.
        :raises: :class:`ValueError <exceptions.ValueError>` if both
                 ``filter_`` and ``append`` are used.
        Nz,At most one of filter_ and append can be set)filter_)
ValueErrorr	   r
   r   )r   row_keyr   appendr   r   r   row^   s    
z	Table.rowc                 C   s(   t || jsdS |j| jko&|j| jkS )NF)
isinstance	__class__r   r   r   otherr   r   r   __eq__   s
    
zTable.__eq__c                 C   s   |  | S r   )r$   r"   r   r   r   __ne__   s    zTable.__ne__r   c                    s   |dur"t jj  fdd|D }d}|rVt }|D ]}|j}|j| |  q6t j|p`g | j	j
| j|d}| j	j}|j||j dS )a  Creates this table.

        .. note::

            A create request returns a
            :class:`._generated.table_pb2.Table` but we don't use
            this response.

        :type initial_split_keys: list
        :param initial_split_keys: (Optional) List of row keys that will be
                                   used to initially split the table into
                                   several tablets (Tablets are similar to
                                   HBase regions). Given two split keys,
                                   ``"s1"`` and ``"s2"``, three tablets will be
                                   created, spanning the key ranges:
                                   ``[, s1)``, ``[s1, s2)``, ``[s2, )``.

        :type column_families: list
        :param column_families: (Optional) List or other iterable of
                                :class:`.ColumnFamily` instances.
        Nc                    s   g | ]} |d qS ))keyr   ).0r&   Zsplit_pbr   r   
<listcomp>   s   z Table.create.<locals>.<listcomp>)Zinitial_splitsparentr   table)table_admin_messages_v2_pb2ZCreateTableRequestZSplittable_v2_pb2r   r   column_familiesZ	MergeFromto_pbr   r   r   _client_table_stubZCreateTabletimeout_seconds)r   Zinitial_split_keysr.   table_pbZcol_famZcurr_id
request_pbclientr   r(   r   create   s&    
zTable.createc                 C   s*   t j| jd}| jj}|j||j dS )zDelete this table.r   N)r,   ZDeleteTableRequestr   r   r0   r1   ZDeleteTabler2   )r   r4   r5   r   r   r   delete   s
    zTable.deletec           	      C   sb   t j| jd}| jj}|j||j}i }|j	 D ](\}}t
|j}| j||d}|||< q4|S )a  List the column families owned by this table.

        :rtype: dict
        :returns: Dictionary of column families attached to this table. Keys
                  are strings (column family names) and values are
                  :class:`.ColumnFamily` instances.
        :raises: :class:`ValueError <exceptions.ValueError>` if the column
                 family name from the response does not agree with the computed
                 name from the column family ID.
        r7   r   )r,   ZGetTableRequestr   r   r0   r1   ZGetTabler2   r.   itemsr   r   r   )	r   r4   r5   r3   resultr   Zvalue_pbr   r   r   r   r   list_column_families   s    

zTable.list_column_familiesc                 C   sn   t | j||d}| jj}|j||j}t|}|  |j	|j
|jfvrRtdt|jdkrddS |j| S )a  Read a single row from this table.

        :type row_key: bytes
        :param row_key: The key of the row to read from.

        :type filter_: :class:`.RowFilter`
        :param filter_: (Optional) The filter to apply to the contents of the
                        row. If unset, returns the entire row.

        :rtype: :class:`.PartialRowData`, :data:`NoneType <types.NoneType>`
        :returns: The contents of the row if any chunks were returned in
                  the response, otherwise :data:`None`.
        :raises: :class:`ValueError <exceptions.ValueError>` if a commit row
                 chunk is never encountered.
        )r   r   z+The row remains partial / is not committed.r   N)_create_row_requestr   r   r0   
_data_stubReadRowsr2   r   Zconsume_allstateZNEW_ROWSTARTr   lenrows)r   r   r   r4   r5   response_iteratorZ	rows_datar   r   r   read_row   s    zTable.read_rowc                 C   s4   t | j||||d}| jj}|j||j}t|S )a  Read rows from this table.

        :type start_key: bytes
        :param start_key: (Optional) The beginning of a range of row keys to
                          read from. The range will include ``start_key``. If
                          left empty, will be interpreted as the empty string.

        :type end_key: bytes
        :param end_key: (Optional) The end of a range of row keys to read from.
                        The range will not include ``end_key``. If left empty,
                        will be interpreted as an infinite string.

        :type limit: int
        :param limit: (Optional) The read will terminate after committing to N
                      rows' worth of results. The default (zero) is to return
                      all results.

        :type filter_: :class:`.RowFilter`
        :param filter_: (Optional) The filter to apply to the contents of the
                        specified row(s). If unset, reads every column in
                        each row.

        :rtype: :class:`.PartialRowsData`
        :returns: A :class:`.PartialRowsData` convenience wrapper for consuming
                  the streamed results.
        )	start_keyend_keyr   limit)r<   r   r   r0   r=   r>   r2   r   )r   rE   rF   rG   r   r4   r5   rC   r   r   r   	read_rows   s    
zTable.read_rowsc                 C   s*   t j| jd}| jj}|j||j}|S )a  Read a sample of row keys in the table.

        The returned row keys will delimit contiguous sections of the table of
        approximately equal size, which can be used to break up the data for
        distributed tasks like mapreduces.

        The elements in the iterator are a SampleRowKeys response and they have
        the properties ``offset_bytes`` and ``row_key``. They occur in sorted
        order. The table might have contents before the first row key in the
        list and after the last one, but a key containing the empty string
        indicates "end of table" and will be the last response given, if
        present.

        .. note::

            Row keys in this list may not have ever been written to or read
            from, and users should therefore not make any assumptions about the
            row key structure that are specific to their use case.

        The ``offset_bytes`` field on a response indicates the approximate
        total storage space used by all rows in the table which precede
        ``row_key``. Buffering the contents of all rows between two subsequent
        samples would require space roughly equal to the difference in their
        ``offset_bytes`` fields.

        :rtype: :class:`grpc.framework.alpha._reexport._CancellableIterator`
        :returns: A cancel-able iterator. Can be consumed by calling ``next()``
                  or by casting to a :class:`list` and can be cancelled by
                  calling ``cancel()``.
        )
table_name)data_messages_v2_pb2ZSampleRowKeysRequestr   r   r0   r=   ZSampleRowKeysr2   )r   r4   r5   rC   r   r   r   sample_row_keys  s    zTable.sample_row_keys)N)NF)Nr   )N)NNNN)__name__
__module____qualname____doc__r   propertyr   r   r   r$   r%   r6   r8   r;   rD   rH   rK   r   r   r   r   r       s    


!
,
  
%r   Nc           	      C   s   d| i}|dur(|dus |dur(t di }|dus<|durd|durPt||d< |durdt||d< |durx| |d< |dur||d< tjf i |}|dur|jjt| |r|jjj	f i | |S )af  Creates a request to read rows in a table.

    :type table_name: str
    :param table_name: The name of the table to read from.

    :type row_key: bytes
    :param row_key: (Optional) The key of a specific row to read from.

    :type start_key: bytes
    :param start_key: (Optional) The beginning of a range of row keys to
                      read from. The range will include ``start_key``. If
                      left empty, will be interpreted as the empty string.

    :type end_key: bytes
    :param end_key: (Optional) The end of a range of row keys to read from.
                    The range will not include ``end_key``. If left empty,
                    will be interpreted as an infinite string.

    :type filter_: :class:`.RowFilter`
    :param filter_: (Optional) The filter to apply to the contents of the
                    specified row(s). If unset, reads the entire table.

    :type limit: int
    :param limit: (Optional) The read will terminate after committing to N
                  rows' worth of results. The default (zero) is to return
                  all results.

    :rtype: :class:`data_messages_v2_pb2.ReadRowsRequest`
    :returns: The ``ReadRowsRequest`` protobuf corresponding to the inputs.
    :raises: :class:`ValueError <exceptions.ValueError>` if both
             ``row_key`` and one of ``start_key`` and ``end_key`` are set
    rI   Nz2Row key and row range cannot be set simultaneouslyZstart_key_closedZend_key_openfilterZ
rows_limit)
r   r   r/   rJ   ZReadRowsRequestrB   Zrow_keysr   Z
row_rangesadd)	rI   r   rE   rF   r   rG   Zrequest_kwargsZrange_kwargsmessager   r   r   r<   A  s.    "r<   )NNNNN)rO   Zgcloud._helpersr   Zgcloud.bigtable._generatedr   rJ   r   r,   r   r-   Zgcloud.bigtable.column_familyr   r   Zgcloud.bigtable.rowr	   r
   r   Zgcloud.bigtable.row_datar   objectr   r<   r   r   r   r   <module>   s      #  