a
    !fG                     @   s(  d Z ddlZddlZddlZddlmZ ddlmZ zddlm	Z	 W n e
yb   ddlmZ	 Y n0 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ZdZdZdZdZdZdZdZedZ ej!Z"dZ#de# Z$de# Z%de# Z&de# Z'dZ(dddZ)G dd de*Z+dd Z,dS )z2Google Cloud Bigtable HappyBase connection module.    N)
interfaces)face)AlreadyExists)Conflict)Client)GCRuleIntersection)MaxAgeGCRule)MaxVersionsGCRule)Table)hostportcompat	transportprotocolz;Cloud Bigtable has no concept of enabled / disabled tables.z;The disable argument should not be used in delete_table(). z,Connection.enable_table(%r) was called, but z-Connection.disable_table(%r) was called, but z0Connection.is_table_enabled(%r) was called, but zConnection.compact_table(%r, major=%r) was called, but the Cloud Bigtable API handles table compactions automatically and does not expose an API for it.c                 C   s   ddi}| dur| d |d< t f i |}z |  | \}}W |  n
|  0 t|dkrjtdt|dkr~tdt|d	krtd
|d S )a  Gets instance for the default project.

    Creates a client with the inferred credentials and project ID from
    the local environment. Then uses
    :meth:`.bigtable.client.Client.list_instances` to
    get the unique instance owned by the project.

    If the request fails for any reason, or if there isn't exactly one instance
    owned by the project, then this function will fail.

    :type timeout: int
    :param timeout: (Optional) The socket timeout in milliseconds.

    :rtype: :class:`gcloud.bigtable.instance.Instance`
    :returns: The unique instance owned by the project inferred from
              the environment.
    :raises ValueError: if there is a failed location or any number of
                        instances other than one.
    ZadminTNg     @@Ztimeout_secondsr   zDDetermining instance via ListInstances encountered failed locations.z1This client doesn't have access to any instances.   zfThis client has access to more than one instance. Please directly pass the instance you'd like to use.)r   startZlist_instancesstoplen
ValueError)timeoutZclient_kwargsclientZ	instancesZfailed_locations r   e/var/www/html/python-backend/venv/lib/python3.9/site-packages/gcloud/bigtable/happybase/connection.py_get_instance@   s    r   c                   @   s   e Zd ZdZdZd"ddZedd Zd	d
 Zdd Z	dd Z
dd Zd#ddZdd Zdd Zd$ddZedd Zedd Zedd Zed%d d!ZdS )&
ConnectionaH  Connection to Cloud Bigtable backend.

    .. note::

        If you pass a ``instance``, it will be :meth:`.Instance.copy`-ed before
        being stored on the new connection. This also copies the
        :class:`Client <gcloud.bigtable.client.Client>` that created the
        :class:`Instance <gcloud.bigtable.instance.Instance>` instance and the
        :class:`Credentials <oauth2client.client.Credentials>` stored on the
        client.

    The arguments ``host``, ``port``, ``compat``, ``transport`` and
    ``protocol`` are allowed (as keyword arguments) for compatibility with
    HappyBase. However, they will not be used in any way, and will cause a
    warning if passed.

    :type timeout: int
    :param timeout: (Optional) The socket timeout in milliseconds.

    :type autoconnect: bool
    :param autoconnect: (Optional) Whether the connection should be
                        :meth:`open`-ed during construction.

    :type table_prefix: str
    :param table_prefix: (Optional) Prefix used to construct table names.

    :type table_prefix_separator: str
    :param table_prefix_separator: (Optional) Separator used with
                                   ``table_prefix``. Defaults to ``_``.

    :type instance: :class:`Instance <gcloud.bigtable.instance.Instance>`
    :param instance: (Optional) A Cloud Bigtable instance. The instance also
                    owns a client for making gRPC requests to the Cloud
                    Bigtable API. If not passed in, defaults to creating client
                    with ``admin=True`` and using the ``timeout`` here for the
                    ``timeout_seconds`` argument to the
                    :class:`Client <gcloud.bigtable.client.Client>`
                    constructor. The credentials for the client
                    will be the implicit ones loaded from the environment.
                    Then that client is used to retrieve all the instances
                    owned by the client's project.

    :type kwargs: dict
    :param kwargs: Remaining keyword arguments. Provided for HappyBase
                   compatibility.
    NT_c                 K   s   |  | |d ur0t|tjs0tdd|t|t|tjsNtdd|t||| _|| _|d u rpt|d| _	n|d urt
d| | _	|r|   d| _d S )Nztable_prefix must be a stringZreceivedz'table_prefix_separator must be a string)r   z:Timeout cannot be used when an existing instance is passedT)_handle_legacy_args
isinstancesixstring_types	TypeErrortypetable_prefixtable_prefix_separatorr   	_instancer   copyopen_initialized)selfr   Zautoconnectr"   r#   instancekwargsr   r   r   __init__   s*    

zConnection.__init__c                 C   s^   t t| }|r0d|}d|f }t| |D ]}| | q4| rZ|  }td|dS )a-  Check legacy HappyBase arguments and warn if set.

        :type arguments_dict: dict
        :param arguments_dict: Unused keyword arguments.

        :raises TypeError: if a keyword other than ``host``, ``port``,
                           ``compat``, ``transport`` or ``protocol`` is used.
        , zRThe HappyBase legacy arguments %s were used. These arguments are unused by gcloud.zReceived unexpected argumentsN)	_LEGACY_ARGSintersectionr   iterkeysjoin_WARNpopkeysr    )Zarguments_dictZcommon_argsall_argsmessageZarg_nameZunexpected_namesr   r   r   r      s    

zConnection._handle_legacy_argsc                 C   s   | j j  dS )a'  Open the underlying transport to Cloud Bigtable.

        This method opens the underlying HTTP/2 gRPC connection using a
        :class:`Client <gcloud.bigtable.client.Client>` bound to the
        :class:`Instance <gcloud.bigtable.instance.Instance>` owned by
        this connection.
        N)r$   _clientr   r(   r   r   r   r&      s    zConnection.openc                 C   s   | j j  dS )a)  Close the underlying transport to Cloud Bigtable.

        This method closes the underlying HTTP/2 gRPC connection using a
        :class:`Client <gcloud.bigtable.client.Client>` bound to the
        :class:`Instance <gcloud.bigtable.instance.Instance>` owned by
        this connection.
        N)r$   r6   r   r7   r   r   r   close   s    zConnection.closec                 C   s   | j d ur|   d S N)r$   r8   r7   r   r   r   __del__   s    
zConnection.__del__c                 C   s   | j du r|S | j | j | S )a  Construct a table name by optionally adding a table name prefix.

        :type name: str
        :param name: The name to have a prefix added to it.

        :rtype: str
        :returns: The prefixed name, if the current connection has a table
                  prefix set.
        N)r"   r#   )r(   namer   r   r   _table_name   s    

zConnection._table_namec                 C   s   |r|  |}t|| S )aR  Table factory.

        :type name: str
        :param name: The name of the table to be created.

        :type use_prefix: bool
        :param use_prefix: Whether to use the table prefix (if any).

        :rtype: :class:`Table <gcloud.bigtable.happybase.table.Table>`
        :returns: Table instance owned by this connection.
        )r<   r
   )r(   r;   Z
use_prefixr   r   r   table   s    
zConnection.tablec                    sL   | j  }dd |D }| jdurH| dt  fdd|D }|S )a  Return a list of table names available to this connection.

        .. note::

            This lists every table in the instance owned by this connection,
            **not** every table that a given user may have access to.

        .. note::

            If ``table_prefix`` is set on this connection, only returns the
            table names which match that prefix.

        :rtype: list
        :returns: List of string table names.
        c                 S   s   g | ]
}|j qS r   )Ztable_id).0Ztable_instancer   r   r   
<listcomp>  s   z%Connection.tables.<locals>.<listcomp>N c                    s"   g | ]}| r| d  qS r9   )
startswith)r>   r;   offsetprefixr   r   r?     s   
)r$   Zlist_tablesr"   r<   r   )r(   Zlow_level_table_instancesZtable_namesr   rB   r   tables  s    


zConnection.tablesc              
      s   t |tstd|s$td|f i }| D ]@\}}t |tjrN|d}|drd|dd }t	|||< q0| 
|}t|| j  fddt|D }z j|d	 W n@ tjy } z&|jtjjkrt|n W Y d}~n
d}~0 0 dS )
a  Create a table.

        .. warning::

            The only column family options from HappyBase that are able to be
            used with Cloud Bigtable are ``max_versions`` and ``time_to_live``.

        Values in ``families`` represent column family options. In HappyBase,
        these are dictionaries, corresponding to the ``ColumnDescriptor``
        structure in the Thrift API. The accepted keys are:

        * ``max_versions`` (``int``)
        * ``compression`` (``str``)
        * ``in_memory`` (``bool``)
        * ``bloom_filter_type`` (``str``)
        * ``bloom_filter_vector_size`` (``int``)
        * ``bloom_filter_nb_hashes`` (``int``)
        * ``block_cache_enabled`` (``bool``)
        * ``time_to_live`` (``int``)

        :type name: str
        :param name: The name of the table to be created.

        :type families: dict
        :param families: Dictionary with column family names as keys and column
                         family options as the values. The options can be among

                         * :class:`dict`
                         * :class:`.GarbageCollectionRule`

        :raises TypeError: If ``families`` is not a dictionary.
        :raises ValueError: If ``families`` has no entries.
        :raises AlreadyExists: If creation fails due to an already
                               existing table.
        :raises NetworkError: If creation fails for a reason other than
                              table exists.
        z!families arg must be a dictionaryz5Cannot create table %r (no column families specified)zutf-8:Nc                 3   s    | ]\}} j ||d V  qdS ))gc_ruleN)Zcolumn_family)r>   column_family_namerH   Zlow_level_tabler   r   	<genexpr>\  s   z*Connection.create_table.<locals>.<genexpr>)column_families)r   dictr    r   itemsr   binary_typedecodeendswith_parse_family_optionr<   _LowLevelTabler$   	iteritemscreater   ZNetworkErrorcoder   Z
StatusCodeZALREADY_EXISTSr   )r(   r;   ZfamiliesZgc_rule_dictrI   optionrL   Znetwork_errr   rJ   r   create_table#  s0    &





zConnection.create_tableFc                 C   s*   |rt t | |}t|| j  dS )a  Delete the specified table.

        :type name: str
        :param name: The name of the table to be deleted. If ``table_prefix``
                     is set, a prefix will be added to the ``name``.

        :type disable: bool
        :param disable: Whether to first disable the table if needed. This
                        is provided for compatibility with HappyBase, but is
                        not relevant for Cloud Bigtable since it has no concept
                        of enabled / disabled tables.
        N)r1   _DISABLE_DELETE_MSGr<   rS   r$   delete)r(   r;   disabler   r   r   delete_tableh  s    
zConnection.delete_tablec                 C   s   t t| f  dS )a'  Enable the specified table.

        .. warning::

            Cloud Bigtable has no concept of enabled / disabled tables so this
            method does nothing. It is provided simply for compatibility.

        :type name: str
        :param name: The name of the table to be enabled.
        N)r1   _ENABLE_TMPLr;   r   r   r   enable_table{  s    zConnection.enable_tablec                 C   s   t t| f  dS )a)  Disable the specified table.

        .. warning::

            Cloud Bigtable has no concept of enabled / disabled tables so this
            method does nothing. It is provided simply for compatibility.

        :type name: str
        :param name: The name of the table to be disabled.
        N)r1   _DISABLE_TMPLr^   r   r   r   disable_table  s    zConnection.disable_tablec                 C   s   t t| f  dS )a  Return whether the specified table is enabled.

        .. warning::

            Cloud Bigtable has no concept of enabled / disabled tables so this
            method always returns :data:`True`. It is provided simply for
            compatibility.

        :type name: str
        :param name: The name of the table to check enabled / disabled status.

        :rtype: bool
        :returns: The value :data:`True` always.
        T)r1   _IS_ENABLED_TMPLr^   r   r   r   is_table_enabled  s    zConnection.is_table_enabledc                 C   s   t t| |f  dS )a  Compact the specified table.

        .. warning::

            Cloud Bigtable supports table compactions, it just doesn't expose
            an API for that feature, so this method does nothing. It is
            provided simply for compatibility.

        :type name: str
        :param name: The name of the table to compact.

        :type major: bool
        :param major: Whether to perform a major compaction.
        N)r1   _COMPACT_TMPL)r;   majorr   r   r   compact_table  s    zConnection.compact_table)NTNr   N)T)F)F)__name__
__module____qualname____doc__r$   r+   staticmethodr   r&   r8   r:   r<   r=   rE   rX   r\   r_   ra   rc   rf   r   r   r   r   r   j   s.   /  




E



r   c                 C   s   | }t |trt| tddgksPddd | D }d|f }t| |d}d}d|v rvtj|d d}d }}|durt	|}|durt
|}|du r|}n|du r|}nt||gd	}|S )
ar  Parses a column family option into a garbage collection rule.

    .. note::

        If ``option`` is not a dictionary, the type is not checked.
        If ``option`` is :data:`None`, there is nothing to do, since this
        is the correct output.

    :type option: :class:`dict`,
                  :data:`NoneType <types.NoneType>`,
                  :class:`.GarbageCollectionRule`
    :param option: A column family option passes as a dictionary value in
                   :meth:`Connection.create_table`.

    :rtype: :class:`.GarbageCollectionRule`
    :returns: A garbage collection rule parsed from the input.
    Zmax_versionsZtime_to_liver,   c                 s   s   | ]}t |V  qd S r9   )repr)r>   keyr   r   r   rK         z'_parse_family_option.<locals>.<genexpr>z_Cloud Bigtable only supports max_versions and time_to_live column family settings. Received: %sN)seconds)rules)r   rM   setr3   r0   r1   getdatetime	timedeltar	   r   r   )rW   resultall_keysZwarning_msgZmax_num_versionsZmax_ageZversions_ruleZage_ruler   r   r   rR     s.    

rR   )N)-rj   rs   warningsr   Z	grpc.betar   Zgrpc.framework.interfaces.facer   Zhappybase.hbase.ttypesr   ImportErrorZgcloud.exceptionsr   Zgcloud.bigtable.clientr   Zgcloud.bigtable.column_familyr   r   r	   Zgcloud.bigtable.happybase.tabler
   Zgcloud.bigtable.tablerS   ZCOMPAT_MODESZTHRIFT_TRANSPORTSZTHRIFT_PROTOCOLSZDEFAULT_HOSTZDEFAULT_PORTZDEFAULT_TRANSPORTZDEFAULT_COMPATDEFAULT_PROTOCOL	frozensetr-   warnr1   Z_BASE_DISABLErY   r]   r`   rb   rd   r   objectr   rR   r   r   r   r   <module>   sP   
*  U