# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['pydbtools']

package_data = \
{'': ['*']}

install_requires = \
['Jinja2>=3.1.0',
 'awswrangler>=2.12.0,<3.0.0',
 'boto3>=1.7.4',
 'pyarrow>=5.0.0',
 'sql-metadata>=2.3.0,<3.0.0',
 'sqlparse>=0.4.1,<0.5.0']

setup_kwargs = {
    'name': 'pydbtools',
    'version': '5.3.2',
    'description': 'A python package to query data via amazon athena and bring it into a pandas df using aws-wrangler.',
    'long_description': '# pydbtools\n\nA package that is used to run SQL queries speficially configured for the Analytical Platform. This packages uses AWS Wrangler\'s Athena module but adds additional functionality (like Jinja templating, creating temporary tables) and alters some configuration to our specification. \n\n## Installation\n\n> Requires a pip release above 20.\n\n```bash\n## To install from pypi\npip install pydbtools\n\n##\xa0Or install from git with a specific release\npip install "pydbtools @ git+https://github.com/moj-analytical-services/pydbtools@v4.0.1"\n```\n\n## Quickstart guide\n\nThe [examples directory](examples) contains more detailed notebooks demonstrating the use of this library, many of which are borrowed from the [mojap-aws-tools-demo repo](https://github.com/moj-analytical-services/mojap-aws-tools-demo). \n\n### Read an SQL Athena query into a pandas dataframe\n\n```python\nimport pydbtools as pydb\ndf = pydb.read_sql_query("SELECT * from a_database.table LIMIT 10")\n```\n\n### Run a query in Athena\n\n```python\nresponse = pydb.start_query_execution_and_wait("CREATE DATABASE IF NOT EXISTS my_test_database")\n```\n\n### Create a temporary table to do further separate SQL queries on later\n\n```python\npydb.create_temp_table("SELECT a_col, count(*) as n FROM a_database.table GROUP BY a_col", table_name="temp_table_1")\ndf = pydb.read_sql_query("SELECT * FROM __temp__.temp_table_1 WHERE n < 10")\n\npydb.dataframe_to_temp_table(my_dataframe, "my_table")\ndf = pydb.read_sql_query("select * from __temp__.my_table where year = 2022")\n```\n\n## Introduction\n\nThis package is a wrapper for [awswrangler](https://aws-data-wrangler.readthedocs.io/en/2.3.0/what.html) that which presets/defines some of the input parameters to the athena module functions to align with our platform setup. See the [awswrangler API reference documentation for Athena](https://aws-data-wrangler.readthedocs.io/en/2.3.0/api.html#amazon-athena) to see what functions you can call from pydbtools.\n\nThe function parameters that are locked down / altered by `pydbtools` are:\n- **boto3_session:** This is auto generated by `pydbtools` (in order to grab the user credentials from the sts client - this is needed for the R version of this package which calls this package under the hood. In short forcing refreshed credentials are needed in R as boto3 credentials timeout and do not refresh when using reticulate, though this does not apply to the latest version of the platform currently being rolled out.)\n- **s3_output:** The S3 path where database queries are written to. This is defined by `pydbtools` based on the IAM user/role calling the query (ensures that each role can only read/write to a S3 path only they can access).\n- **database:** Will either be set to `None` or `__temp__` depending on other user parameters (if `ctas_approach=True`). `__temp__` is an alias to an autogenerated temp database name which is generated from `pydbtools` again based on the IAM user/role. References to this temporary database can be referenced by the keyword `__temp__` in SQL queries see additional functionality to awswrangler section.\n- **sql:** We allows reference to the database name `__temp__` which is an alias to a user specific temporary database. When a function call has an SQL parameter the SQL is checked with an SQL parser and then any reference to `__temp__` as a database is replaced with the actual database name which is autogenerated. This replacement only occurs for `SELECT` queries.\n- **pyarrow_additional_kwargs:** This is set to `{"coerce_int96_timestamp_unit": "ms", "timestamp_as_object": True}` by default. Doing this solves [this awswrangler issue](https://github.com/awslabs/aws-data-wrangler/issues/592))\n\n## Additional Functionality\n\nAs well as acting as a wrapper function for awswrangler this package also allows you to do the following:\n\n### Run query and wait for a response\n\nThis function essentially calls two functions from `awswrangler.athena`. First `start_query_execution` followed by `wait_query`.\n\n```python\nimport pydbtools as pydb\n\nresponse = pydb.start_query_execution_and_wait("SELECT * from a_database.table LIMIT 10")\n```\n\n### Create Temporary Tables\n\nYou can use the `create_temp_table` function to write SQL to create a store a temporary table that sits in your `__temp__` database.\n\n```python\nimport pydbtools as pydb\n\npydb.create_temp_table("SELECT * from a_database.table LIMIT 10", table_name="temp_table_1")\ndf = pydb.read_sql_query("SELECT * from __temp__.temp_table_1")\ndf.head()\n```\n\nSee [the example notebook](examples/create_temporary_tables.ipynb) for a more detailed example.\n\n\n### Run SQL from a string of statements or a file\n\nIt wil often be more convenient to write your SQL in an editor with language support rather than as a Python string. You can create temporary tables within SQL using the syntax below.\n\n```python\nimport pydbtools as pydb\n\nsql = """\ncreate temp table A as (\n    select * from database.table1\n    where year = 2021\n);\n\ncreate temp table B as (\n    select * from database.table2\n    where amount > 10\n);\n\nselect * from __temp__.A\nleft join __temp__.B\non A.id = B.id;\n"""\n\nwith open("queries.sql", "w") as f:\n    f.write(sql)\n    \nwith open("queries.sql", "r") as f:\n    df = pydb.read_sql_queries(f.read())\n```\n\nMultiple `SELECT` queries can be returned as a generator of dataframes using `read_sql_queries_gen`.\n\nSee [the notebook on creating temporary tables with SQL](examples/create_temporary_tables_from_sql_file.ipynb) and [the notebook on database administration with SQL](examples/creating_and_maintaining_database_tables_in_athena_from_sql.ipynb) for more detailed examples.\n\nAdditionally you can use [Jinja](https://jinja.palletsprojects.com/en/3.0.x/) templating to inject arguments into your SQL.\n\n```python\nsql_template = """\nSELECT *\nFROM {{ db_name }}.{{ table }}\n"""\nsql = pydb.render_sql_template(sql_template, {"db_name": db_name, "table": "department"})\npydb.read_sql_query(sql)\n\nwith open("tempfile.sql", "w") as f:\n    f.write("SELECT * FROM {{ db_name }}.{{ table_name }}")\nsql = pydb.get_sql_from_file("tempfile.sql", jinja_args={"db_name": db_name, "table_name": "department"})\npydb.read_sql_query(sql)\n"""\n```\n\nSee the [notebook on SQL templating](examples/sql_templating.ipynb) for more details.\n \n### Delete databases, tables and partitions together with the data on S3\n\n```python\nimport pydbtools as pydb\n\npydb.delete_partitions_and_data(database=\'my_database\', table=\'my_table\', expression=\'year = 2020 or year = 2021\')\npydb.delete_table_and_data(database=\'my_database\', table=\'my_table\')\npydb.delete_database(\'my_database\')\n\n# These can be used for temporary databases and tables.\npydb.delete_table_and_data(database=\'__temp__\', table=\'my_temp_table\')\n```\n\nFor more details see [the notebook on deletions](examples/delete_databases_tables_and_partitions.ipynb).\n\n## Usage / Examples\n\n### Simple \n\n```python\nimport pydbtools as pydb\n\n# Run a query using pydbtools\nresponse = pydb.start_query_execution_and_wait("CREATE DATABASE IF NOT EXISTS my_test_database")\n\n# Read data from an athena query directly into pandas\npydb.read_sql("SELECT * from a_database.table LIMIT 10")\n\n# Create a temp table to do further seperate SQL queries later on\npydb.create_temp_table("SELECT a_col, count(*) as n FROM a_database.table GROUP BY a_col", table_name="temp_table_1")\ndf = pydb.read_sql_query("SELECT * FROM __temp__.temp_table_1 WHERE n < 10")\n```\n\n### More advanced usage\n\nGet the actual name for your temp database, create your temp db then delete it using awswrangler (note: `awswrangler` will raise an error if the database does not exist)\n\n```python\nimport awswrangler as wr\nimport pydbtools as pydb\n\nuser_id, out_path = pydb.get_user_id_and_table_dir()\ntemp_db_name = pydb.get_database_name_from_userid(user_id)\nprint(temp_db_name)\npydb.create_temp_table()\nprint(wr.catalog.delete_database(name=temp_db_name))\n```\n\n# DEPRECATED\n\n## Functions\n\nThe functions:\n- `pydbtools.get_athena_query_response`\n- `pydbtools.read_sql`\n\nAre now deprecated and calls to these functions will raise an warning. They have been replaced by `pydbtools.start_query_execution_and_wait` and `pydbtools.read_sql_query`.\n\n## Docs for versions below v3.0.0\n\nThis is a simple package that let\'s you query databases using Amazon Athena and get the s3 path to the athena out (as a csv). This is significantly faster than using the the database drivers so might be a good option when pulling in large data. By default, data is converted into a pandas dataframe with equivalent column data types as the Athena table - see "Meta Data" section below.\n\nNote to use this package you need to be added to the StandardDatabaseAccess IAM Policy on the Analytical Platform. Please contact the team if you require access.\n\nTo install...\n\n```\npip install pydbtools\n```\n\nOr from github...\n\n```\npip install git+git://github.com/moj-analytical-services/pydbtools.git#egg=pydbtools\n```\n\npackage requirements are:\n\n* `pandas` _(preinstalled)_\n* `boto3` _(preinstalled)_\n* `numpy` _(preinstalled)_\n* `s3fs`\n* `gluejobutils`\n\n## Usage\n\nMost simple way to use pydbtools. This will return a pandas df reprentation of the data (with matching meta data).\n\n```python\nimport pydbtools as pydb\n\n# Run SQL query and return as a pandas df\ndf = pydb.read_sql("SELECT * from database.table limit 10000")\ndf.head()\n```\n\nYou might want to cast the data yourself or read all the columns as strings.\n\n```python\nimport pydbtools as pydb\n\n# Run SQL query and return as a pandas df\ndf = pydb.read_sql("SELECT * from database.table limit 10000", cols_as_str=True)\ndf.head()\n\ndf.dtypes # all objects\n```\n\nYou can also pass additional arguments to the pandas.read_csv that reads the resulting Athena SQL query.\nNote you cannot pass dtype as this is specified within the `read_sql` function.\n\n```python\nimport pydbtools as pydb\n\n# pass nrows parameter to pandas.read_csv function\npydb.read_sql("SELECT * from database.table limit 10000", nrows=20)\n```\n\nIf you didn\'t want to read the data into pandas you can run the SQL query and get the s3 path and meta data \nof the output using the get_athena_query_response. The data is then read in using `boto3`, `io` and `csv`. \n\n\n```python\nimport pydbtools as pydb\nimport io\nimport csv\nimport boto3\n\nresponse = pydb.get_athena_query_response("SELECT * from database.table limit 10000")\n\n# print out path to athena query output (as a csv)\nprint(response[\'s3_path\'])\n\n# print out meta data\nprint(response[\'meta\'])\n\n# Read the csv into a string in memory\ns3_resource = boto3.resource(\'s3\')\nbucket, key = response[\'s3_path\'].replace("s3://", "").split(\'/\', 1)\nobj = s3_resource.Object(bucket, key)\ntext = obj.get()[\'Body\'].read().decode(\'utf-8\')\n\n# Use csv reader to print the outputting csv\nreader = csv.reader(text.split(\'\\n\'), delimiter=\',\')\nfor row in reader:\n    print(\'\\t\'.join(row))\n```\n\n## Meta data\n\nThe output from get_athena_query_response(...) is a dictionary one of it\'s keys is `meta`. The meta key is a list where each element in this list is the name (`name`) and data type (`type`) for each column in your athena query output. For example for this table output:\n\n|col1|col2|\n|---|---|\n|1|2018-01-01|\n|2|2018-01-02|\n...\n\nWould have a meta like:\n\n```python\nfor m in response[\'meta\']:\n    print(m[\'name\'], m[\'type\'])\n```\n\noutput:\n\n```\n> col1 int\n> col1 date\n```\n\nThe meta types follow those listed as the generic meta data types used in [etl_manager](https://github.com/moj-analytical-services/etl_manager). If you want the actual athena meta data instead you can get them instead of the generic meta data types by setting the `return_athena_types` input parameter to `True` e.g.\n\n```python\nresponse = pydb.get_athena_query_response("SELECT * from database.table limit 10000", return_athena_types=True)\n\nprint(response[\'meta\'])\n```\n\nIf you wish to read your SQL query directly into a pandas dataframe you can use the read_sql function. You can apply `*args` or `**kwargs` into this function which are passed down to `pd.read_csv()`.\n\n```python\nimport pydbtools as pydb\n\ndf = pydb.read_sql("SELECT * FROM database.table limit 1000")\ndf.head()\n```\n\n### Meta data conversion\n\nBelow is a table that explains what the conversion is from our data types to a pandas df (using the `read_sql` function):\n\n| data type | pandas column type| Comment                                                                                 |\n|-----------|-------------------|-----------------------------------------------------------------------------------------|\n| character | object            | [see here](https://stackoverflow.com/questions/34881079/pandas-distinction-between-str-and-object-types)|\n| int       | np.float64        | Pandas integers do not allow nulls so using floats                                      |\n| long      | np.float64        | Pandas integers do not allow nulls so using floats                                      |\n| date      | pandas timestamp  |                                                                                         |\n| datetime  | pandas timestamp  |                                                                                         |\n| boolean   | np.bool           |                                                                                         |\n| float     | np.float64        |                                                                                         |\n| double    | np.float64        |                                                                                         |\n| decimal    | np.float64        |                                                                                         |\n\n## Unit tests\nUnit tests run in unittest through Poetry. Run `poetry run python -m unittest` to activate them. If you\'ve changed any dependencies, run `poetry update` first.\n\nThe tests run against a test Glue database callled `dbtools`. They use data stored on s3 in `alpha-dbtools-test-bucket`.\n\n#### Notes:\n\n- Amazon Athena using a flavour of SQL called presto docs can be found [here](https://prestodb.io/docs/current/)\n- To query a date column in Athena you need to specify that your value is a date e.g. `SELECT * FROM db.table WHERE date_col > date \'2018-12-31\'`\n- To query a datetime or timestamp column in Athena you need to specify that your value is a timestamp e.g. `SELECT * FROM db.table WHERE datetime_col > timestamp \'2018-12-31 23:59:59\'`\n- Note dates and datetimes formatting used above. See more specifics around date and datetimes [here](https://prestodb.io/docs/current/functions/datetime.html)\n- To specify a string in the sql query always use \'\' not "". Using ""\'s means that you are referencing a database, table or col, etc.\n- When data is pulled back into rStudio the column types are either R characters (for any col that was a dates, datetimes, characters) or doubles (for everything else).\n\nSee changelog for release changes\n',
    'author': 'Karik Isichei',
    'author_email': 'karik.isichei@digital.justice.gov.uk',
    'maintainer': 'None',
    'maintainer_email': 'None',
    'url': 'None',
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.8,<3.11',
}


setup(**setup_kwargs)
