PyHive


NamePyHive JSON
Version 0.7.0 PyPI version JSON
download
home_pagehttps://github.com/dropbox/PyHive
SummaryPython interface to Hive
upload_time2023-08-17 23:29:25
maintainer
docs_urlNone
authorJing Wang
requires_python
licenseApache License, Version 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage
            ================================
Project is currently unsupported
================================




.. image:: https://travis-ci.org/dropbox/PyHive.svg?branch=master
    :target: https://travis-ci.org/dropbox/PyHive
.. image:: https://img.shields.io/codecov/c/github/dropbox/PyHive.svg

======
PyHive
======

PyHive is a collection of Python `DB-API <http://www.python.org/dev/peps/pep-0249/>`_ and
`SQLAlchemy <http://www.sqlalchemy.org/>`_ interfaces for `Presto <http://prestodb.io/>`_ ,
`Hive <http://hive.apache.org/>`_ and `Trino <https://trino.io/>`_.

Usage
=====

DB-API
------
.. code-block:: python

    from pyhive import presto  # or import hive or import trino
    cursor = presto.connect('localhost').cursor()  # or use hive.connect or use trino.connect
    cursor.execute('SELECT * FROM my_awesome_data LIMIT 10')
    print cursor.fetchone()
    print cursor.fetchall()

DB-API (asynchronous)
---------------------
.. code-block:: python

    from pyhive import hive
    from TCLIService.ttypes import TOperationState
    cursor = hive.connect('localhost').cursor()
    cursor.execute('SELECT * FROM my_awesome_data LIMIT 10', async=True)

    status = cursor.poll().operationState
    while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
        logs = cursor.fetch_logs()
        for message in logs:
            print message

        # If needed, an asynchronous query can be cancelled at any time with:
        # cursor.cancel()

        status = cursor.poll().operationState

    print cursor.fetchall()

In Python 3.7 `async` became a keyword; you can use `async_` instead:

.. code-block:: python

    cursor.execute('SELECT * FROM my_awesome_data LIMIT 10', async_=True)


SQLAlchemy
----------
First install this package to register it with SQLAlchemy, see ``entry_points`` in ``setup.py``.

.. code-block:: python

    from sqlalchemy import *
    from sqlalchemy.engine import create_engine
    from sqlalchemy.schema import *
    # Presto
    engine = create_engine('presto://localhost:8080/hive/default')
    # Trino
    engine = create_engine('trino+pyhive://localhost:8080/hive/default')
    # Hive
    engine = create_engine('hive://localhost:10000/default')

    # SQLAlchemy < 2.0
    logs = Table('my_awesome_data', MetaData(bind=engine), autoload=True)
    print select([func.count('*')], from_obj=logs).scalar()

    # Hive + HTTPS + LDAP or basic Auth
    engine = create_engine('hive+https://username:password@localhost:10000/')
    logs = Table('my_awesome_data', MetaData(bind=engine), autoload=True)
    print select([func.count('*')], from_obj=logs).scalar()

    # SQLAlchemy >= 2.0
    metadata_obj = MetaData()
    books = Table("books", metadata_obj, Column("id", Integer), Column("title", String), Column("primary_author", String))
    metadata_obj.create_all(engine)
    inspector = inspect(engine)
    inspector.get_columns('books')

    with engine.connect() as con:
        data = [{ "id": 1, "title": "The Hobbit", "primary_author": "Tolkien" }, 
                { "id": 2, "title": "The Silmarillion", "primary_author": "Tolkien" }]
        con.execute(books.insert(), data[0])
        result = con.execute(text("select * from books"))
        print(result.fetchall())

Note: query generation functionality is not exhaustive or fully tested, but there should be no
problem with raw SQL.

Passing session configuration
-----------------------------

.. code-block:: python

    # DB-API
    hive.connect('localhost', configuration={'hive.exec.reducers.max': '123'})
    presto.connect('localhost', session_props={'query_max_run_time': '1234m'})
    trino.connect('localhost',  session_props={'query_max_run_time': '1234m'})
    # SQLAlchemy
    create_engine(
        'presto://user@host:443/hive',
        connect_args={'protocol': 'https',
                      'session_props': {'query_max_run_time': '1234m'}}
    )
    create_engine(
        'trino+pyhive://user@host:443/hive',
        connect_args={'protocol': 'https',
                      'session_props': {'query_max_run_time': '1234m'}}
    )
    create_engine(
        'hive://user@host:10000/database',
        connect_args={'configuration': {'hive.exec.reducers.max': '123'}},
    )
    # SQLAlchemy with LDAP
    create_engine(
        'hive://user:password@host:10000/database',
        connect_args={'auth': 'LDAP'},
    )

Requirements
============

Install using

- ``pip install 'pyhive[hive]'`` or ``pip install 'pyhive[hive_pure_sasl]'`` for the Hive interface
- ``pip install 'pyhive[presto]'`` for the Presto interface
- ``pip install 'pyhive[trino]'`` for the Trino interface

Note: ``'pyhive[hive]'`` extras uses `sasl <https://pypi.org/project/sasl/>`_ that doesn't support Python 3.11, See `github issue <https://github.com/cloudera/python-sasl/issues/30>`_.
Hence PyHive also supports `pure-sasl <https://pypi.org/project/pure-sasl/>`_ via additional extras ``'pyhive[hive_pure_sasl]'`` which support Python 3.11.

PyHive works with

- Python 2.7 / Python 3
- For Presto: `Presto installation <https://prestodb.io/docs/current/installation.html>`_
- For Trino: `Trino installation <https://trino.io/docs/current/installation.html>`_
- For Hive: `HiveServer2 <https://cwiki.apache.org/confluence/display/Hive/Setting+up+HiveServer2>`_ daemon

Changelog
=========
See https://github.com/dropbox/PyHive/releases.

Contributing
============
- Please fill out the Dropbox Contributor License Agreement at https://opensource.dropbox.com/cla/ and note this in your pull request.
- Changes must come with tests, with the exception of trivial things like fixing comments. See .travis.yml for the test environment setup.
- Notes on project scope:

  - This project is intended to be a minimal Hive/Presto client that does that one thing and nothing else.
    Features that can be implemented on top of PyHive, such integration with your favorite data analysis library, are likely out of scope.
  - We prefer having a small number of generic features over a large number of specialized, inflexible features.
    For example, the Presto code takes an arbitrary ``requests_session`` argument for customizing HTTP calls, as opposed to having a separate parameter/branch for each ``requests`` option.

Tips for test environment setup
================================
You can setup test environment by following ``.travis.yaml`` in this repository. It uses `Cloudera's CDH 5 <https://docs.cloudera.com/documentation/enterprise/release-notes/topics/cdh_vd_cdh_download_510.html>`_ which requires username and password for download.
It may not be feasible for everyone to get those credentials. Hence below are alternative instructions to setup test environment.

You can clone `this repository <https://github.com/big-data-europe/docker-hive/blob/master/docker-compose.yml>`_ which has Docker Compose setup for Presto and Hive.
You can add below lines to its docker-compose.yaml to start Trino in same environment::
 
    trino:
        image: trinodb/trino:351    
        ports:     
            - "18080:18080"    
        volumes:    
            - ./trino:/etc/trino

Note: ``./trino`` for docker volume defined above is `trino config from PyHive repository <https://github.com/dropbox/PyHive/tree/master/scripts/travis-conf/trino>`_

Then run::
    docker-compose up -d

Testing
=======
.. image:: https://travis-ci.org/dropbox/PyHive.svg
    :target: https://travis-ci.org/dropbox/PyHive
.. image:: http://codecov.io/github/dropbox/PyHive/coverage.svg?branch=master
    :target: http://codecov.io/github/dropbox/PyHive?branch=master

Run the following in an environment with Hive/Presto::

    ./scripts/make_test_tables.sh
    virtualenv --no-site-packages env
    source env/bin/activate
    pip install -e .
    pip install -r dev_requirements.txt
    py.test

WARNING: This drops/creates tables named ``one_row``, ``one_row_complex``, and ``many_rows``, plus a
database called ``pyhive_test_database``.

Updating TCLIService
====================

The TCLIService module is autogenerated using a ``TCLIService.thrift`` file. To update it, the
``generate.py`` file can be used: ``python generate.py <TCLIServiceURL>``. When left blank, the
version for Hive 2.3 will be downloaded.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/dropbox/PyHive",
    "name": "PyHive",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Jing Wang",
    "author_email": "jing@dropbox.com",
    "download_url": "https://files.pythonhosted.org/packages/f6/ec/5c658b3a4d99a6d9145030cc8e003c3f7efc668d866e88544812ab0af310/PyHive-0.7.0.tar.gz",
    "platform": null,
    "description": "================================\nProject is currently unsupported\n================================\n\n\n\n\n.. image:: https://travis-ci.org/dropbox/PyHive.svg?branch=master\n    :target: https://travis-ci.org/dropbox/PyHive\n.. image:: https://img.shields.io/codecov/c/github/dropbox/PyHive.svg\n\n======\nPyHive\n======\n\nPyHive is a collection of Python `DB-API <http://www.python.org/dev/peps/pep-0249/>`_ and\n`SQLAlchemy <http://www.sqlalchemy.org/>`_ interfaces for `Presto <http://prestodb.io/>`_ ,\n`Hive <http://hive.apache.org/>`_ and `Trino <https://trino.io/>`_.\n\nUsage\n=====\n\nDB-API\n------\n.. code-block:: python\n\n    from pyhive import presto  # or import hive or import trino\n    cursor = presto.connect('localhost').cursor()  # or use hive.connect or use trino.connect\n    cursor.execute('SELECT * FROM my_awesome_data LIMIT 10')\n    print cursor.fetchone()\n    print cursor.fetchall()\n\nDB-API (asynchronous)\n---------------------\n.. code-block:: python\n\n    from pyhive import hive\n    from TCLIService.ttypes import TOperationState\n    cursor = hive.connect('localhost').cursor()\n    cursor.execute('SELECT * FROM my_awesome_data LIMIT 10', async=True)\n\n    status = cursor.poll().operationState\n    while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):\n        logs = cursor.fetch_logs()\n        for message in logs:\n            print message\n\n        # If needed, an asynchronous query can be cancelled at any time with:\n        # cursor.cancel()\n\n        status = cursor.poll().operationState\n\n    print cursor.fetchall()\n\nIn Python 3.7 `async` became a keyword; you can use `async_` instead:\n\n.. code-block:: python\n\n    cursor.execute('SELECT * FROM my_awesome_data LIMIT 10', async_=True)\n\n\nSQLAlchemy\n----------\nFirst install this package to register it with SQLAlchemy, see ``entry_points`` in ``setup.py``.\n\n.. code-block:: python\n\n    from sqlalchemy import *\n    from sqlalchemy.engine import create_engine\n    from sqlalchemy.schema import *\n    # Presto\n    engine = create_engine('presto://localhost:8080/hive/default')\n    # Trino\n    engine = create_engine('trino+pyhive://localhost:8080/hive/default')\n    # Hive\n    engine = create_engine('hive://localhost:10000/default')\n\n    # SQLAlchemy < 2.0\n    logs = Table('my_awesome_data', MetaData(bind=engine), autoload=True)\n    print select([func.count('*')], from_obj=logs).scalar()\n\n    # Hive + HTTPS + LDAP or basic Auth\n    engine = create_engine('hive+https://username:password@localhost:10000/')\n    logs = Table('my_awesome_data', MetaData(bind=engine), autoload=True)\n    print select([func.count('*')], from_obj=logs).scalar()\n\n    # SQLAlchemy >= 2.0\n    metadata_obj = MetaData()\n    books = Table(\"books\", metadata_obj, Column(\"id\", Integer), Column(\"title\", String), Column(\"primary_author\", String))\n    metadata_obj.create_all(engine)\n    inspector = inspect(engine)\n    inspector.get_columns('books')\n\n    with engine.connect() as con:\n        data = [{ \"id\": 1, \"title\": \"The Hobbit\", \"primary_author\": \"Tolkien\" }, \n                { \"id\": 2, \"title\": \"The Silmarillion\", \"primary_author\": \"Tolkien\" }]\n        con.execute(books.insert(), data[0])\n        result = con.execute(text(\"select * from books\"))\n        print(result.fetchall())\n\nNote: query generation functionality is not exhaustive or fully tested, but there should be no\nproblem with raw SQL.\n\nPassing session configuration\n-----------------------------\n\n.. code-block:: python\n\n    # DB-API\n    hive.connect('localhost', configuration={'hive.exec.reducers.max': '123'})\n    presto.connect('localhost', session_props={'query_max_run_time': '1234m'})\n    trino.connect('localhost',  session_props={'query_max_run_time': '1234m'})\n    # SQLAlchemy\n    create_engine(\n        'presto://user@host:443/hive',\n        connect_args={'protocol': 'https',\n                      'session_props': {'query_max_run_time': '1234m'}}\n    )\n    create_engine(\n        'trino+pyhive://user@host:443/hive',\n        connect_args={'protocol': 'https',\n                      'session_props': {'query_max_run_time': '1234m'}}\n    )\n    create_engine(\n        'hive://user@host:10000/database',\n        connect_args={'configuration': {'hive.exec.reducers.max': '123'}},\n    )\n    # SQLAlchemy with LDAP\n    create_engine(\n        'hive://user:password@host:10000/database',\n        connect_args={'auth': 'LDAP'},\n    )\n\nRequirements\n============\n\nInstall using\n\n- ``pip install 'pyhive[hive]'`` or ``pip install 'pyhive[hive_pure_sasl]'`` for the Hive interface\n- ``pip install 'pyhive[presto]'`` for the Presto interface\n- ``pip install 'pyhive[trino]'`` for the Trino interface\n\nNote: ``'pyhive[hive]'`` extras uses `sasl <https://pypi.org/project/sasl/>`_ that doesn't support Python 3.11, See `github issue <https://github.com/cloudera/python-sasl/issues/30>`_.\nHence PyHive also supports `pure-sasl <https://pypi.org/project/pure-sasl/>`_ via additional extras ``'pyhive[hive_pure_sasl]'`` which support Python 3.11.\n\nPyHive works with\n\n- Python 2.7 / Python 3\n- For Presto: `Presto installation <https://prestodb.io/docs/current/installation.html>`_\n- For Trino: `Trino installation <https://trino.io/docs/current/installation.html>`_\n- For Hive: `HiveServer2 <https://cwiki.apache.org/confluence/display/Hive/Setting+up+HiveServer2>`_ daemon\n\nChangelog\n=========\nSee https://github.com/dropbox/PyHive/releases.\n\nContributing\n============\n- Please fill out the Dropbox Contributor License Agreement at https://opensource.dropbox.com/cla/ and note this in your pull request.\n- Changes must come with tests, with the exception of trivial things like fixing comments. See .travis.yml for the test environment setup.\n- Notes on project scope:\n\n  - This project is intended to be a minimal Hive/Presto client that does that one thing and nothing else.\n    Features that can be implemented on top of PyHive, such integration with your favorite data analysis library, are likely out of scope.\n  - We prefer having a small number of generic features over a large number of specialized, inflexible features.\n    For example, the Presto code takes an arbitrary ``requests_session`` argument for customizing HTTP calls, as opposed to having a separate parameter/branch for each ``requests`` option.\n\nTips for test environment setup\n================================\nYou can setup test environment by following ``.travis.yaml`` in this repository. It uses `Cloudera's CDH 5 <https://docs.cloudera.com/documentation/enterprise/release-notes/topics/cdh_vd_cdh_download_510.html>`_ which requires username and password for download.\nIt may not be feasible for everyone to get those credentials. Hence below are alternative instructions to setup test environment.\n\nYou can clone `this repository <https://github.com/big-data-europe/docker-hive/blob/master/docker-compose.yml>`_ which has Docker Compose setup for Presto and Hive.\nYou can add below lines to its docker-compose.yaml to start Trino in same environment::\n \n    trino:\n        image: trinodb/trino:351    \n        ports:     \n            - \"18080:18080\"    \n        volumes:    \n            - ./trino:/etc/trino\n\nNote: ``./trino`` for docker volume defined above is `trino config from PyHive repository <https://github.com/dropbox/PyHive/tree/master/scripts/travis-conf/trino>`_\n\nThen run::\n    docker-compose up -d\n\nTesting\n=======\n.. image:: https://travis-ci.org/dropbox/PyHive.svg\n    :target: https://travis-ci.org/dropbox/PyHive\n.. image:: http://codecov.io/github/dropbox/PyHive/coverage.svg?branch=master\n    :target: http://codecov.io/github/dropbox/PyHive?branch=master\n\nRun the following in an environment with Hive/Presto::\n\n    ./scripts/make_test_tables.sh\n    virtualenv --no-site-packages env\n    source env/bin/activate\n    pip install -e .\n    pip install -r dev_requirements.txt\n    py.test\n\nWARNING: This drops/creates tables named ``one_row``, ``one_row_complex``, and ``many_rows``, plus a\ndatabase called ``pyhive_test_database``.\n\nUpdating TCLIService\n====================\n\nThe TCLIService module is autogenerated using a ``TCLIService.thrift`` file. To update it, the\n``generate.py`` file can be used: ``python generate.py <TCLIServiceURL>``. When left blank, the\nversion for Hive 2.3 will be downloaded.\n",
    "bugtrack_url": null,
    "license": "Apache License, Version 2.0",
    "summary": "Python interface to Hive",
    "version": "0.7.0",
    "project_urls": {
        "Homepage": "https://github.com/dropbox/PyHive"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f6ec5c658b3a4d99a6d9145030cc8e003c3f7efc668d866e88544812ab0af310",
                "md5": "94fe30ee618df449105d4b2f04ec3a55",
                "sha256": "585beff9578a61b99aed47140fec97e26323e8c685a5b5d0c8550a8ebf8a24e0"
            },
            "downloads": -1,
            "filename": "PyHive-0.7.0.tar.gz",
            "has_sig": false,
            "md5_digest": "94fe30ee618df449105d4b2f04ec3a55",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 46479,
            "upload_time": "2023-08-17T23:29:25",
            "upload_time_iso_8601": "2023-08-17T23:29:25.260139Z",
            "url": "https://files.pythonhosted.org/packages/f6/ec/5c658b3a4d99a6d9145030cc8e003c3f7efc668d866e88544812ab0af310/PyHive-0.7.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-17 23:29:25",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "dropbox",
    "github_project": "PyHive",
    "travis_ci": true,
    "coveralls": true,
    "github_actions": false,
    "lcname": "pyhive"
}
        
Elapsed time: 0.10524s