a
    !fb3                     @   sn   d Z ddlZddlZddlZddlmZ ddlmZ e Z	ej
ddZejZdZG dd	 d	eZdddZdS )z-Google Cloud Bigtable HappyBase batch module.    N)_datetime_from_microseconds)TimestampRange  )microsecondszFThe wal argument (Write-Ahead-Log) is not supported by Cloud Bigtable.c                   @   sl   e Zd ZdZdddefddZdd Zdd	 Zd
d ZefddZ	dd Z
defddZdd Zdd ZdS )Batcha  Batch class for accumulating mutations.

    .. note::

       When using a batch with ``transaction=False`` as a context manager
       (i.e. in a ``with`` statement), mutations will still be sent as
       row mutations even if the context manager exits with an error.
       This behavior is in place to match the behavior in the HappyBase
       HBase / Thrift implementation.

    :type table: :class:`Table <gcloud.bigtable.happybase.table.Table>`
    :param table: The table where mutations will be applied.

    :type timestamp: int
    :param timestamp: (Optional) Timestamp (in milliseconds since the epoch)
                      that all mutations will be applied at.

    :type batch_size: int
    :param batch_size: (Optional) The maximum number of mutations to allow
                       to accumulate before committing them.

    :type transaction: bool
    :param transaction: Flag indicating if the mutations should be sent
                        transactionally or not. If ``transaction=True`` and
                        an error occurs while a :class:`Batch` is active,
                        then none of the accumulated mutations will be
                        committed. If ``batch_size`` is set, the mutation
                        can't be transactional.

    :type wal: object
    :param wal: Unused parameter (Boolean for using the HBase Write Ahead Log).
                Provided for compatibility with HappyBase, but irrelevant for
                Cloud Bigtable since it does not have a Write Ahead Log.

    :raises: :class:`TypeError <exceptions.TypeError>` if ``batch_size``
             is set and ``transaction=True``.
             :class:`ValueError <exceptions.ValueError>` if ``batch_size``
             is not positive.
    NFc                 C   s   |t urtt |d ur4|r$td|dkr4td|| _|| _d  | _| _|d urxt	d| | _| jt
 }t|d| _|| _i | _d| _d S )Nz7When batch_size is set, a Batch cannot be transactionalr   zbatch_size must be positiver   )end)_WAL_SENTINEL_WARN_WAL_WARNING	TypeError
ValueError_table_batch_size
_timestamp_delete_ranger   _ONE_MILLISECONDr   _transaction_row_map_mutation_count)selftable	timestampZ
batch_sizeZtransactionwalZnext_timestamp r   `/var/www/html/python-backend/venv/lib/python3.9/site-packages/gcloud/bigtable/happybase/batch.py__init__L   s"    
zBatch.__init__c                 C   s,   | j  D ]}|  q
| j   d| _dS )z3Send / commit the batch of mutations to the server.r   N)r   valuescommitclearr   )r   rowr   r   r   sendm   s    

z
Batch.sendc                 C   s   | j r| j| j kr|   dS )z>Send / commit the batch if mutations have exceeded batch size.N)r   r   r    r   r   r   r   	_try_sendv   s    zBatch._try_sendc                 C   s,   || j vr"| jj}||| j |< | j | S )aq  Gets a row that will hold mutations.

        If the row is not already cached on the current batch, a new row will
        be created.

        :type row_key: str
        :param row_key: The row key for a row stored in the map.

        :rtype: :class:`Row <gcloud.bigtable.row.Row>`
        :returns: The newly created or stored row that will hold mutations.
        )r   r   Z_low_level_tabler   )r   Zrow_keyr   r   r   r   _get_row{   s    
zBatch._get_rowc           	      C   s|   |t urtt | |}tt|dd}|D ],\}}||d |  }|j|||| jd q0|  j	t
|7  _	|   dS )a  Insert data into a row in the table owned by this batch.

        :type row: str
        :param row: The row key where the mutation will be "put".

        :type data: dict
        :param data: Dictionary containing the data to be inserted. The keys
                     are columns names (of the form ``fam:col``) and the values
                     are strings (bytes) to be stored in those columns.

        :type wal: object
        :param wal: Unused parameter (to over-ride the default on the
                    instance). Provided for compatibility with HappyBase, but
                    irrelevant for Cloud Bigtable since it does not have a
                    Write Ahead Log.
        T)require_qualifier:)r   N)r   r	   r
   r#   _get_column_pairssixiterkeysZset_cellr   r   lenr"   )	r   r   datar   
row_objectcolumn_pairscolumn_family_idcolumn_qualifiervaluer   r   r   put   s    

z	Batch.putc                 C   sX   t |}|D ]F\}}|du r@| jdur.td|j||jd q|j||| jd qdS )a  Adds delete mutations for a list of columns and column families.

        :type columns: list
        :param columns: Iterable containing column names (as
                        strings). Each column name can be either

                          * an entire column family: ``fam`` or ``fam:``
                          * a single column: ``fam:col``

        :type row_object: :class:`Row <gcloud_bigtable.row.Row>`
        :param row_object: The row which will hold the delete mutations.

        :raises: :class:`ValueError <exceptions.ValueError>` if the delete
                 timestamp range is set on the current batch, but a
                 column family delete is attempted.
        NzQThe Cloud Bigtable API does not support adding a timestamp to "DeleteFromFamily" )columns)Z
time_range)r&   r   r   Zdelete_cellsZALL_COLUMNSZdelete_cell)r   r1   r+   r,   r-   r.   r   r   r   _delete_columns   s    
zBatch._delete_columnsc                 C   sv   |t urtt | |}|du rL| jdur4td|  |  jd7  _n| || |  jt	|7  _| 
  dS )a  Delete data from a row in the table owned by this batch.

        :type row: str
        :param row: The row key where the delete will occur.

        :type columns: list
        :param columns: (Optional) Iterable containing column names (as
                        strings). Each column name can be either

                          * an entire column family: ``fam`` or ``fam:``
                          * a single column: ``fam:col``

                        If not used, will delete the entire row.

        :type wal: object
        :param wal: Unused parameter (to over-ride the default on the
                    instance). Provided for compatibility with HappyBase, but
                    irrelevant for Cloud Bigtable since it does not have a
                    Write Ahead Log.

        :raises: If the delete timestamp range is set on the
                 current batch, but a full row delete is attempted.
        NzWThe Cloud Bigtable API does not support adding a timestamp to "DeleteFromRow" mutations   )r   r	   r
   r#   r   r   deleter   r2   r)   r"   )r   r   r1   r   r+   r   r   r   r4      s    

zBatch.deletec                 C   s   | S )z*Enter context manager, no set-up required.r   r!   r   r   r   	__enter__   s    zBatch.__enter__c                 C   s   | j r|durdS |   dS )a  Exit context manager, no set-up required.

        :type exc_type: type
        :param exc_type: The type of the exception if one occurred while the
                         context manager was active. Otherwise, :data:`None`.

        :type exc_value: :class:`Exception <exceptions.Exception>`
        :param exc_value: An instance of ``exc_type`` if an exception occurred
                          while the context was active.
                          Otherwise, :data:`None`.

        :type traceback: ``traceback`` type
        :param traceback: The traceback where the exception occurred (if one
                          did occur). Otherwise, :data:`None`.
        N)r   r    )r   exc_type	exc_value	tracebackr   r   r   __exit__   s    zBatch.__exit__)__name__
__module____qualname____doc__r   r   r    r"   r#   r0   r2   r4   r5   r9   r   r   r   r   r   #   s   (
!	!+r   Fc                 C   s   g }| D ]}t |tjr"|d}|dr8|dd }|d}|dkrj|rZtd|q||dg q|dkr||d qtdq|S )	au  Turns a list of column or column families into parsed pairs.

    Turns a column family (``fam`` or ``fam:``) into a pair such
    as ``['fam', None]`` and turns a column (``fam:col``) into
    ``['fam', 'col']``.

    :type columns: list
    :param columns: Iterable containing column names (as
                    strings). Each column name can be either

                      * an entire column family: ``fam`` or ``fam:``
                      * a single column: ``fam:col``

    :type require_qualifier: bool
    :param require_qualifier: Boolean indicating if the columns should
                              all have a qualifier or not.

    :rtype: list
    :returns: List of pairs, where the first element in each pair is the
              column family and the second is the column qualifier
              (or :data:`None`).
    :raises: :class:`ValueError <exceptions.ValueError>` if any of the columns
             are not of the expected format.
             :class:`ValueError <exceptions.ValueError>` if
             ``require_qualifier`` is :data:`True` and one of the values is
             for an entire column family
    zutf-8r%   Nr   z#column does not contain a qualifierr3   z.Column contains the : separator more than once)	
isinstancer'   binary_typedecodeendswithcountr   appendsplit)r1   r$   r,   columnZ
num_colonsr   r   r   r&     s"    



r&   )F)r=   datetimewarningsr'   Zgcloud._helpersr   Zgcloud.bigtable.row_filtersr   objectr   	timedeltar   warnr	   r
   r   r&   r   r   r   r   <module>   s    t