### Setup Development Environment Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Commands to initialize a virtual environment and install the package in editable mode for development. ```bash virtualenv .venv . .venv/bin/activate pip install . pip install -e .[tests] ``` -------------------------------- ### Setup Development Environment with pyenv Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Commands to install pyenv, configure multiple Python versions, and prepare the environment for tox execution. ```shell curl https://pyenv.run | bash pyenv install 3.9, 3.10, 3.11, 3.12, 3.13 pyenv versions pyenv shell 3.13.2 3.12.9 3.11.11 3.10.16 3.9.21 pip install tox tox ``` -------------------------------- ### Quick Start - DBAPI Interface Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Demonstrates how to connect to Trino and execute a query using the DBAPI interface. ```APIDOC ## Quick Start - DBAPI Interface ### Description Connect to Trino using the DBAPI interface and execute a query to retrieve system information. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example ```python import aiotrino conn = aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='the-catalog', schema='the-schema', ) cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() await conn.close() ``` ### Response #### Success Response (200) - **rows** (list) - A list of rows returned by the query. #### Response Example ```json [ {"name": "node1", "state": "alive"}, {"name": "node2", "state": "alive"} ] ``` ``` -------------------------------- ### Quick Start - Context Manager Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Shows how to use a context manager for connecting to Trino and executing queries. ```APIDOC ## Quick Start - Context Manager ### Description Utilize a context manager for a more streamlined connection and query execution process with Trino. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example ```python import aiotrino async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='the-catalog', schema='the-schema', ) as conn: cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() ``` ### Response #### Success Response (200) - **rows** (list) - A list of rows returned by the query. #### Response Example ```json [ {"name": "node1", "state": "alive"}, {"name": "node2", "state": "alive"} ] ``` ``` -------------------------------- ### Install aiotrino via pip Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md The standard command to install the aiotrino package into your Python environment. ```bash pip install aiotrino ``` -------------------------------- ### Integrate Aiotrino with SQLAlchemy Async Engine Source: https://context7.com/mvanderlee/aiotrino/llms.txt Provides an example of using aiotrino with SQLAlchemy's async engine for ORM-style database access. Shows how to create an async engine with the aiotrino dialect and execute raw SQL queries. ```python import asyncio from sqlalchemy import Column, Integer, String, create_engine, text from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.orm import declarative_base, Session async def sqlalchemy_example(): # Create async engine with aiotrino dialect engine = create_async_engine( 'aiotrino://user@localhost:8080/hive/default', echo=True, ) async with engine.connect() as conn: # Execute raw SQL result = await conn.execute(text('SELECT * FROM system.runtime.nodes')) rows = result.fetchall() for row in rows: print(row) await engine.dispose() asyncio.run(sqlalchemy_example()) ``` -------------------------------- ### Describe Query Output Columns with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Illustrates how to use the `describe` method in aiotrino to get information about query output columns without actually executing the query. This is useful for understanding the schema of query results beforehand. ```python import aiotrino import asyncio async def describe_output(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='tpch', schema='tiny', ) as conn: cur = await conn.cursor() # Describe the output columns of a query output = await cur.describe('SELECT orderkey, custkey, totalprice FROM orders') for col in output: print(f"Column: {col.name}") print(f" Catalog: {col.catalog}") print(f" Schema: {col.schema}") print(f" Table: {col.table}") print(f" Type: {col.type}") print(f" Aliased: {col.aliased}") print() asyncio.run(describe_output()) ``` -------------------------------- ### JWT Token Authentication with aiotrino in Python Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates connecting to Trino clusters configured for JWT authentication using the JWTAuthentication class. This example shows how to list available catalogs after authentication. ```python import aiotrino import asyncio async def jwt_authenticated_query(): conn = aiotrino.dbapi.connect( host='coordinator.example.com', port=8443, catalog='hive', schema='default', http_scheme='https', auth=aiotrino.auth.JWTAuthentication(token="your-jwt-token-here"), ) cur = await conn.cursor() await cur.execute('SHOW CATALOGS') catalogs = await cur.fetchall() print(f"Available catalogs: {[cat[0] for cat in catalogs]}") await conn.close() asyncio.run(jwt_authenticated_query()) ``` -------------------------------- ### Authenticate with Trino Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Examples of connecting to a Trino cluster using Basic (LDAP) or JWT token authentication. ```python import aiotrino conn = aiotrino.dbapi.connect( host='coordinator url', port=8443, user='the-user', catalog='the-catalog', schema='the-schema', http_scheme='https', auth=aiotrino.auth.BasicAuthentication("principal id", "password"), ) cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() await conn.close() ``` ```python import aiotrino conn = aiotrino.dbapi.connect( host='coordinator url', port=8443, catalog='the-catalog', schema='the-schema', http_scheme='https', auth=aiotrino.auth.JWTAuthentication(token="jwt-token"), ) cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() await conn.close() ``` -------------------------------- ### Configure Trino Session Properties with Aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Shows how to set Trino session properties for query optimization and behavior control when connecting with aiotrino. Includes examples of setting query execution and run times, and hash generation optimization. Verifies settings by querying 'SHOW SESSION'. ```python import aiotrino import asyncio async def session_properties(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', session_properties={ 'query_max_execution_time': '1h', 'query_max_run_time': '2h', 'optimize_hash_generation': 'true', }, ) as conn: cur = await conn.cursor() # Verify session properties await cur.execute('SHOW SESSION') sessions = await cur.fetchall() for name, value, default, type_, description in sessions: if 'query_max' in name or 'optimize_hash' in name: print(f"{name}: {value} (default: {default})") asyncio.run(session_properties()) ``` -------------------------------- ### SQLAlchemy Connection URL Format with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates various ways to configure SQLAlchemy connection URLs for aiotrino, including basic, authenticated, JWT, session properties, client tags, and SSL verification settings. These examples show how to construct the URL string with different parameters. ```python from sqlalchemy.ext.asyncio import create_async_engine import json import urllib.parse # Basic connection engine_basic = create_async_engine( 'aiotrino://user@localhost:8080/catalog/schema' ) # With basic authentication engine_auth = create_async_engine( 'aiotrino://username:password@localhost:8443/catalog/schema' ) # With JWT authentication engine_jwt = create_async_engine( 'aiotrino://localhost:8443/catalog/schema?access_token=your-jwt-token' ) # With session properties session_props = json.dumps({'query_max_execution_time': '1h'}) engine_session = create_async_engine( f'aiotrino://user@localhost:8080/catalog/schema?session_properties={urllib.parse.quote(session_props)}' ) # With client tags client_tags = json.dumps(['etl', 'production']) engine_tags = create_async_engine( f'aiotrino://user@localhost:8080/catalog/schema?client_tags={urllib.parse.quote(client_tags)}' ) # With SSL verification disabled (for development) engine_no_verify = create_async_engine( 'aiotrino://user@localhost:8443/catalog/schema?verify=false' ) ``` -------------------------------- ### Error Handling Source: https://context7.com/mvanderlee/aiotrino/llms.txt Provides examples of how to handle various Trino-specific errors and generic DBAPI exceptions, including TrinoUserError, TrinoExternalError, TrinoQueryError, TrinoConnectionError, DatabaseError, and ProgrammingError. ```APIDOC ## Error Handling Handle Trino-specific errors and DBAPI exceptions properly. ### Example Usage ```python import aiotrino from aiotrino.exceptions import ( TrinoQueryError, TrinoUserError, TrinoExternalError, TrinoConnectionError, DatabaseError, ProgrammingError, ) import asyncio async def error_handling(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', ) as conn: cur = await conn.cursor() try: await cur.execute('SELECT * FROM nonexistent_table') await cur.fetchall() except TrinoUserError as e: # User errors (syntax, table not found, permission denied) print(f"User Error: {e.message}") print(f"Error Code: {e.error_code}") print(f"Error Name: {e.error_name}") print(f"Query ID: {e.query_id}") if e.error_location: line, col = e.error_location print(f"Error at line {line}, column {col}") except TrinoExternalError as e: # External errors (connector issues, resource unavailable) print(f"External Error: {e.message}") except TrinoQueryError as e: # General query errors print(f"Query Error: {e.message}") print(f"Failure Info: {e.failure_info}") except TrinoConnectionError as e: # Connection failures print(f"Connection Error: {e}") except DatabaseError as e: # Generic database errors print(f"Database Error: {e}") asyncio.run(error_handling()) ``` ``` -------------------------------- ### Cancel Running Query with Aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates how to programmatically cancel a long-running Trino query using aiotrino. It involves starting a query, waiting for a short period, and then issuing a cancel command. Handles potential asyncio.CancelledError. ```python import aiotrino import asyncio async def cancel_query(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='tpch', schema='sf1', ) as conn: cur = await conn.cursor() # Start a potentially long query query_task = asyncio.create_task( cur.execute('SELECT * FROM lineitem') ) # Wait a bit then cancel await asyncio.sleep(0.5) # Cancel the query await cur.cancel() print(f"Query {cur.query_id} cancelled") # Clean up the task try: await query_task except asyncio.CancelledError: pass asyncio.run(cancel_query()) ``` -------------------------------- ### Error Handling with aiotrino DBAPI Source: https://context7.com/mvanderlee/aiotrino/llms.txt Shows how to properly handle Trino-specific errors and general DBAPI exceptions when interacting with Trino using the aiotrino library. It includes examples of catching various exceptions like TrinoUserError, TrinoExternalError, and DatabaseError. ```python import aiotrino from aiotrino.exceptions import ( TrinoQueryError, TrinoUserError, TrinoExternalError, TrinoConnectionError, DatabaseError, ProgrammingError, ) import asyncio async def error_handling(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', ) as conn: cur = await conn.cursor() try: await cur.execute('SELECT * FROM nonexistent_table') await cur.fetchall() except TrinoUserError as e: # User errors (syntax, table not found, permission denied) print(f"User Error: {e.message}") print(f"Error Code: {e.error_code}") print(f"Error Name: {e.error_name}") print(f"Query ID: {e.query_id}") if e.error_location: line, col = e.error_location print(f"Error at line {line}, column {col}") except TrinoExternalError as e: # External errors (connector issues, resource unavailable) print(f"External Error: {e.message}") except TrinoQueryError as e: # General query errors print(f"Query Error: {e.message}") print(f"Failure Info: {e.failure_info}") except TrinoConnectionError as e: # Connection failures print(f"Connection Error: {e}") except DatabaseError as e: # Generic database errors print(f"Database Error: {e}") asyncio.run(error_handling()) ``` -------------------------------- ### Basic Connection and Query Execution in Python Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates how to establish a basic connection to a Trino cluster using aiotrino and execute a SQL query. It covers fetching all results and manually closing the connection. ```python import aiotrino import asyncio async def basic_query(): # Create a connection to Trino conn = aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', ) # Get a cursor and execute a query cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') # Fetch all results rows = await cur.fetchall() for row in rows: print(row) # Always close the connection await conn.close() asyncio.run(basic_query()) ``` -------------------------------- ### Retrieve Query Results with Fetch Methods Source: https://context7.com/mvanderlee/aiotrino/llms.txt Shows how to retrieve data using fetchone, fetchmany, and fetchall. Explains how to control batch sizes using the arraysize attribute. ```python import aiotrino import asyncio async def fetch_methods(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='tpch', schema='tiny', ) as conn: cur = await conn.cursor() await cur.execute('SELECT * FROM nation ORDER BY nationkey') # Fetch single row first_row = await cur.fetchone() print(f"First row: {first_row}") # Fetch multiple rows (default arraysize is 1) cur.arraysize = 5 batch = await cur.fetchmany() # Returns up to 5 rows print(f"Batch of {len(batch)} rows: {batch}") # Fetch specific number of rows specific_batch = await cur.fetchmany(size=3) print(f"Specific batch: {specific_batch}") # Fetch all remaining rows remaining = await cur.fetchall() print(f"Remaining {len(remaining)} rows") asyncio.run(fetch_methods()) ``` -------------------------------- ### Connect and Query Trino Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Demonstrates connecting to a Trino instance and executing a query using both standard connection and context manager patterns. ```python import aiotrino conn = aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='the-catalog', schema='the-schema', ) cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() await conn.close() ``` ```python import aiotrino async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='the-catalog', schema='the-schema', ) as conn: cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() ``` -------------------------------- ### Basic Connection and Query Execution Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates how to establish a basic connection to a Trino cluster and execute SQL queries using the DBAPI interface. It also shows how to fetch all results from a query. ```APIDOC ## Basic Connection and Query Execution ### Description Connect to a Trino cluster and execute SQL queries using the DBAPI interface. The connection supports async context managers for automatic resource cleanup. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A (Illustrative Example) ### Request Example ```python import aiotrino import asyncio async def basic_query(): # Create a connection to Trino conn = aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', ) # Get a cursor and execute a query cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') # Fetch all results rows = await cur.fetchall() for row in rows: print(row) # Always close the connection await conn.close() asyncio.run(basic_query()) ``` ### Response #### Success Response (200) N/A (Illustrative Example) #### Response Example ``` # Example output for each row ('node-1', 'http://localhost:8080', 'ACTIVE') ('node-2', 'http://localhost:8081', 'ACTIVE') ... ``` ``` -------------------------------- ### Basic Authentication with aiotrino in Python Source: https://context7.com/mvanderlee/aiotrino/llms.txt Shows how to connect to Trino clusters configured for LDAP using BasicAuthentication, enabling username and password authentication over HTTPS. It demonstrates fetching the current user. ```python import aiotrino import asyncio async def authenticated_query(): conn = aiotrino.dbapi.connect( host='coordinator.example.com', port=8443, user='the-user', catalog='hive', schema='default', http_scheme='https', auth=aiotrino.auth.BasicAuthentication("username", "password"), ) cur = await conn.cursor() await cur.execute('SELECT current_user') result = await cur.fetchone() print(f"Current user: {result[0]}") await conn.close() asyncio.run(authenticated_query()) ``` -------------------------------- ### Add Client Tags and Extra Credentials with Aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Illustrates how to add client tags for query tracking and provide extra credentials for connector authentication when using aiotrino to connect to Trino. Demonstrates setting tags and credential pairs during connection. ```python import aiotrino import asyncio async def tags_and_credentials(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', client_tags=['etl', 'production', 'team-data'], extra_credential=[ ('hive.hdfs.impersonation.principal', 'service_account'), ('hive.metastore.username', 'metastore_user'), ], ) as conn: cur = await conn.cursor() await cur.execute('SELECT current_user') result = await cur.fetchone() print(f"Query executed with user: {result[0]}") asyncio.run(tags_and_credentials()) ``` -------------------------------- ### Connection with Context Manager in Python Source: https://context7.com/mvanderlee/aiotrino/llms.txt Illustrates using async context managers with aiotrino for automatic connection lifecycle management, ensuring the connection is properly closed upon exiting the context. It also shows how to retrieve column descriptions. ```python import aiotrino import asyncio async def query_with_context(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', ) as conn: cur = await conn.cursor() await cur.execute('SELECT node_id, http_uri, state FROM system.runtime.nodes') rows = await cur.fetchall() # Get column descriptions description = await cur.get_description() column_names = [col.name for col in description] print(f"Columns: {column_names}") print(f"Results: {rows}") asyncio.run(query_with_context()) ``` -------------------------------- ### Execute Parameterized Queries with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates how to safely execute SQL queries using prepared statements to prevent SQL injection. Supports various data types including strings, dates, decimals, arrays, and UUIDs. ```python import aiotrino import asyncio from datetime import datetime, date from decimal import Decimal import uuid async def parameterized_queries(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='memory', schema='default', ) as conn: cur = await conn.cursor() # Query with string parameter await cur.execute( "SELECT * FROM users WHERE name = ?", ["John Doe"] ) # Query with multiple parameters of different types await cur.execute( "SELECT * FROM orders WHERE customer_id = ? AND order_date > ? AND total > ?", [12345, date(2024, 1, 1), Decimal('99.99')] ) # Query with array parameter await cur.execute( "SELECT * FROM products WHERE category IN (SELECT * FROM UNNEST(?))", [['electronics', 'books', 'clothing']] ) # Query with UUID parameter await cur.execute( "SELECT * FROM sessions WHERE session_id = ?", [uuid.UUID('550e8400-e29b-41d4-a716-446655440000')] ) rows = await cur.fetchall() print(rows) asyncio.run(parameterized_queries()) ``` -------------------------------- ### Custom HTTP Session with aiohttp Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates how to provide a custom aiohttp ClientSession for advanced HTTP configuration when connecting to Trino. This allows for fine-grained control over connection pooling, DNS caching, timeouts, and other network-related settings, enhancing performance and reliability. ```python import aiotrino import aiohttp import asyncio async def custom_http_session(): # Create custom connector with specific settings connector = aiohttp.TCPConnector( limit=100, # Connection pool size ttl_dns_cache=300, # DNS cache TTL enable_cleanup_closed=True, ) # Create custom session with timeout settings timeout = aiohttp.ClientTimeout(total=120, connect=10) http_session = aiohttp.ClientSession( connector=connector, timeout=timeout, ) try: conn = aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', http_session=http_session, ) cur = await conn.cursor() await cur.execute('SELECT 1') result = await cur.fetchone() print(result) await conn.close() finally: await http_session.close() asyncio.run(custom_http_session()) ``` -------------------------------- ### Low-Level Client API with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Illustrates the usage of the low-level TrinoRequest and TrinoQuery classes for advanced control over Trino interactions. This includes setting up a client session, creating a request handler, executing a query, iterating over results, and accessing query metadata. ```python import aiotrino.client import asyncio async def low_level_api(): # Create client session client_session = aiotrino.client.ClientSession( user='the-user', catalog='tpch', schema='tiny', source='my-application', ) # Create request handler request = aiotrino.client.TrinoRequest( host='localhost', port=8080, client_session=client_session, max_attempts=5, request_timeout=60.0, ) # Create and execute query query = aiotrino.client.TrinoQuery( request=request, query='SELECT * FROM nation LIMIT 5', ) result = await query.execute() # Iterate over results async for row in result: print(row) # Access query metadata print(f"Query ID: {query.query_id}") print(f"Stats: {query.stats}") await request.close() asyncio.run(low_level_api()) ``` -------------------------------- ### Low-Level Client API Source: https://context7.com/mvanderlee/aiotrino/llms.txt Illustrates how to use the low-level TrinoRequest and TrinoQuery classes for advanced control over HTTP requests and query execution, including creating a client session, request handler, executing queries, and accessing metadata. ```APIDOC ## Low-Level Client API Use the low-level TrinoRequest and TrinoQuery classes for advanced control over HTTP requests and query execution. ### Example Usage ```python import aiotrino.client import asyncio async def low_level_api(): # Create client session client_session = aiotrino.client.ClientSession( user='the-user', catalog='tpch', schema='tiny', source='my-application', ) # Create request handler request = aiotrino.client.TrinoRequest( host='localhost', port=8080, client_session=client_session, max_attempts=5, request_timeout=60.0, ) # Create and execute query query = aiotrino.client.TrinoQuery( request=request, query='SELECT * FROM nation LIMIT 5', ) result = await query.execute() # Iterate over results async for row in result: print(row) # Access query metadata print(f"Query ID: {query.query_id}") print(f"Stats: {query.stats}") await request.close() asyncio.run(low_level_api()) ``` ``` -------------------------------- ### Set Catalog Roles for Access Control with Aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates how to configure catalog-specific roles for fine-grained access control in Trino using aiotrino. Shows setting roles for different catalogs and querying granted roles. ```python import aiotrino import asyncio async def roles_config(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', roles={ 'hive': 'admin_role', 'system': 'ALL', }, ) as conn: cur = await conn.cursor() # Query current roles await cur.execute('SHOW ROLE GRANTS') roles = await cur.fetchall() for role in roles: print(f"Role: {role}") asyncio.run(roles_config()) ``` -------------------------------- ### Release Package to PyPI Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Sequence of commands to build distribution files and upload them to PyPI using twine. ```bash . .venv/bin/activate && pip install twine wheel && rm -rf dist/ && ./setup.py sdist bdist_wheel && twine upload dist/* && open https://pypi.org/project/aiotrino/ && echo "Released!" ``` -------------------------------- ### Connection with Context Manager Source: https://context7.com/mvanderlee/aiotrino/llms.txt Illustrates using async context managers for automatic connection lifecycle management, ensuring the connection is properly closed upon exiting the context. ```APIDOC ## Connection with Context Manager ### Description Use async context managers for automatic connection lifecycle management. The connection will be properly closed when exiting the context. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A (Illustrative Example) ### Request Example ```python import aiotrino import asyncio async def query_with_context(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', ) as conn: cur = await conn.cursor() await cur.execute('SELECT node_id, http_uri, state FROM system.runtime.nodes') rows = await cur.fetchall() # Get column descriptions description = await cur.get_description() column_names = [col.name for col in description] print(f"Columns: {column_names}") print(f"Results: {rows}") asyncio.run(query_with_context()) ``` ### Response #### Success Response (200) N/A (Illustrative Example) #### Response Example ``` Columns: ['node_id', 'http_uri', 'state'] Results: [('node-1', 'http://localhost:8080', 'ACTIVE'), ('node-2', 'http://localhost:8081', 'ACTIVE')] ``` ``` -------------------------------- ### Manual Transaction Control with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates how to manually control transaction commit and rollback using aiotrino for fine-grained control over transaction boundaries. It connects to a database, performs operations, and explicitly commits or rolls back changes. ```python import aiotrino from aiotrino import transaction import asyncio async def manual_transaction(): conn = aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', isolation_level=transaction.IsolationLevel.READ_COMMITTED, ) try: cur = await conn.cursor() await cur.execute('INSERT INTO logs (message) VALUES (?)', ['Operation started']) await cur.fetchone() # Explicit commit await conn.commit() print("Changes committed") await cur.execute('INSERT INTO logs (message) VALUES (?)', ['Another operation']) await cur.fetchone() # Explicit rollback await conn.rollback() print("Changes rolled back") finally: await conn.close() asyncio.run(manual_transaction()) ``` -------------------------------- ### Run Test Suites Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Commands to execute unit and integration tests. Uses pytest for standard testing and tox for multi-version environment testing. ```shell ./run tests pytest tests pytest integration_tests tox ``` -------------------------------- ### PrestoSQL Compatibility with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Explains how to achieve backwards compatibility with PrestoSQL by overriding the default HTTP headers used by aiotrino. This is achieved by setting `aiotrino.constants.HEADERS` to `aiotrino.constants.PrestoHeaders` at application startup. ```python import aiotrino import asyncio # Override headers at application startup for Presto compatibility aiotrino.constants.HEADERS = aiotrino.constants.PrestoHeaders async def presto_compatible(): async with aiotrino.dbapi.connect( host='presto-coordinator.example.com', port=8080, user='the-user', catalog='hive', schema='default', ) as conn: cur = await conn.cursor() await cur.execute('SELECT 1') result = await cur.fetchone() print(result) asyncio.run(presto_compatible()) ``` -------------------------------- ### PrestoSQL Compatibility Source: https://context7.com/mvanderlee/aiotrino/llms.txt Explains how to enable backwards compatibility with PrestoSQL by overriding the default HTTP headers used by aiotrino. ```APIDOC ## PrestoSQL Compatibility Enable backwards compatibility with PrestoSQL by overriding the HTTP headers. ### Example Usage ```python import aiotrino import asyncio # Override headers at application startup for Presto compatibility aiotrino.constants.HEADERS = aiotrino.constants.PrestoHeaders async def presto_compatible(): async with aiotrino.dbapi.connect( host='presto-coordinator.example.com', port=8080, user='the-user', catalog='hive', schema='default', ) as conn: cur = await conn.cursor() await cur.execute('SELECT 1') result = await cur.fetchone() print(result) asyncio.run(presto_compatible()) ``` ``` -------------------------------- ### Query Metadata and Statistics with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Shows how to access query metadata, including query ID, statistics, column descriptions, and row counts, after executing a query. It connects to a Trino database and retrieves detailed information about the executed query. ```python import aiotrino import asyncio async def query_metadata(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='tpch', schema='tiny', ) as conn: cur = await conn.cursor() await cur.execute('SELECT * FROM orders LIMIT 100') await cur.fetchall() # Query ID for debugging and monitoring print(f"Query ID: {cur.query_id}") # Info URI for Trino UI print(f"Info URI: {cur.info_uri}") # Query statistics stats = cur.stats print(f"Statistics: {stats}") # Column descriptions description = await cur.get_description() for col in description: print(f"Column: {col.name}, Type: {col.type_code}") # Row count for INSERT/UPDATE/DELETE print(f"Row count: {cur.rowcount}") # Any warnings warnings = cur.warnings if warnings: print(f"Warnings: {warnings}") asyncio.run(query_metadata()) ``` -------------------------------- ### Configure Timezone for Query Processing with Aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Explains how to configure the timezone for Trino query processing using aiotrino to ensure correct handling of temporal data. Shows setting a specific timezone and querying current timezone and timestamps. ```python import aiotrino import asyncio async def timezone_config(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', timezone='America/New_York', ) as conn: cur = await conn.cursor() # Query current timezone await cur.execute('SELECT current_timezone()') tz = await cur.fetchone() print(f"Query timezone: {tz[0]}") # Timestamp handling respects timezone await cur.execute("SELECT TIMESTAMP '2024-01-15 10:30:00'") ts = await cur.fetchone() print(f"Timestamp: {ts[0]}") asyncio.run(timezone_config()) ``` -------------------------------- ### SQLAlchemy Connection URL Format Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates various ways to configure SQLAlchemy connections using aiotrino's URL format, including basic authentication, JWT, session properties, client tags, and SSL verification. ```APIDOC ## SQLAlchemy Connection URL Format Configure SQLAlchemy connections using URL parameters for authentication and session settings. ### Basic Connection ```python from sqlalchemy.ext.asyncio import create_async_engine engine_basic = create_async_engine( 'aiotrino://user@localhost:8080/catalog/schema' ) ``` ### Basic Authentication ```python engine_auth = create_async_engine( 'aiotrino://username:password@localhost:8443/catalog/schema' ) ``` ### JWT Authentication ```python engine_jwt = create_async_engine( 'aiotrino://localhost:8443/catalog/schema?access_token=your-jwt-token' ) ``` ### Session Properties ```python import json import urllib.parse session_props = json.dumps({'query_max_execution_time': '1h'}) engine_session = create_async_engine( f'aiotrino://user@localhost:8080/catalog/schema?session_properties={urllib.parse.quote(session_props)}' ) ``` ### Client Tags ```python import json import urllib.parse client_tags = json.dumps(['etl', 'production']) engine_tags = create_async_engine( f'aiotrino://user@localhost:8080/catalog/schema?client_tags={urllib.parse.quote(client_tags)}' ) ``` ### SSL Verification Disabled ```python engine_no_verify = create_async_engine( 'aiotrino://user@localhost:8443/catalog/schema?verify=false' ) ``` ``` -------------------------------- ### Execute Many Statements with aiotrino Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates the use of `executemany` in aiotrino to execute the same SQL statement multiple times with different parameter sets. This is efficient for bulk inserts or updates. ```python import aiotrino import asyncio async def execute_many(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='memory', schema='default', ) as conn: cur = await conn.cursor() # Create table first await cur.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER, name VARCHAR, email VARCHAR ) ''') await cur.fetchall() # Insert multiple rows with executemany users_data = [ [1, 'Alice', 'alice@example.com'], [2, 'Bob', 'bob@example.com'], [3, 'Charlie', 'charlie@example.com'], ] await cur.executemany( 'INSERT INTO users (id, name, email) VALUES (?, ?, ?)', users_data ) print(f"Inserted rows, last rowcount: {cur.rowcount}") asyncio.run(execute_many()) ``` -------------------------------- ### Basic Authentication Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Connect to a Trino cluster configured with LDAP using Basic Authentication. ```APIDOC ## Basic Authentication ### Description Connect to a Trino cluster that uses LDAP for authentication by providing a principal ID and password. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters - **host** (string) - Required - The hostname or IP address of the Trino coordinator. - **port** (integer) - Required - The port number for the Trino coordinator. - **user** (string) - Required - The user principal. - **catalog** (string) - Required - The catalog to use. - **schema** (string) - Required - The schema to use. - **http_scheme** (string) - Required - The HTTP scheme to use ('http' or 'https'). - **auth** (object) - Required - An instance of `aiotrino.auth.BasicAuthentication` containing the principal and password. ### Request Example ```python import aiotrino conn = aiotrino.dbapi.connect( host='coordinator url', port=8443, user='the-user', catalog='the-catalog', schema='the-schema', http_scheme='https', auth=aiotrino.auth.BasicAuthentication("principal id", "password"), ) cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() await conn.close() ``` ### Response #### Success Response (200) - **rows** (list) - A list of rows returned by the query. #### Response Example ```json [ {"name": "node1", "state": "alive"} ] ``` ``` -------------------------------- ### Manage Transactions with Isolation Levels Source: https://context7.com/mvanderlee/aiotrino/llms.txt Explains how to perform ACID-compliant transactions by setting an isolation level. The context manager handles automatic commits and rollbacks. ```python import aiotrino from aiotrino import transaction import asyncio async def transaction_example(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='hive', schema='default', isolation_level=transaction.IsolationLevel.REPEATABLE_READ, ) as conn: cur = await conn.cursor() try: # First statement in transaction await cur.execute('INSERT INTO accounts (id, balance) VALUES (1, 1000)') await cur.fetchone() # Second statement in same transaction await cur.execute('INSERT INTO accounts (id, balance) VALUES (2, 500)') await cur.fetchone() # Transaction commits automatically on successful context exit print("Transaction committed successfully") except Exception as e: # Transaction rolls back automatically on error print(f"Transaction rolled back due to: {e}") asyncio.run(transaction_example()) ``` -------------------------------- ### Configure PrestoSQL Compatibility Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Overrides default headers to ensure compatibility with legacy PrestoSQL environments. ```python import aiotrino aiotrino.constants.HEADERS = aiotrino.constants.PrestoHeaders ``` -------------------------------- ### Iterate Over Results Asynchronously Source: https://context7.com/mvanderlee/aiotrino/llms.txt Demonstrates the use of the cursor as an asynchronous iterator to process query results row by row efficiently. ```python import aiotrino import asyncio async def async_iteration(): async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='tpch', schema='tiny', ) as conn: cur = await conn.cursor() await cur.execute('SELECT nationkey, name, regionkey FROM nation') # Iterate asynchronously over results async for row in cur: nationkey, name, regionkey = row print(f"Nation {nationkey}: {name} (Region: {regionkey})") asyncio.run(async_iteration()) ``` -------------------------------- ### JWT Token Authentication Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Connect to a Trino cluster using JWT (JSON Web Token) authentication. ```APIDOC ## JWT Token Authentication ### Description Connect to a Trino cluster by providing a JWT token for authentication. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters - **host** (string) - Required - The hostname or IP address of the Trino coordinator. - **port** (integer) - Required - The port number for the Trino coordinator. - **catalog** (string) - Required - The catalog to use. - **schema** (string) - Required - The schema to use. - **http_scheme** (string) - Required - The HTTP scheme to use ('http' or 'https'). - **auth** (object) - Required - An instance of `aiotrino.auth.JWTAuthentication` containing the JWT token. ### Request Example ```python import aiotrino conn = aiotrino.dbapi.connect( host='coordinator url', port=8443, catalog='the-catalog', schema='the-schema', http_scheme='https', auth=aiotrino.auth.JWTAuthentication(token="jwt-token"), ) cur = await conn.cursor() await cur.execute('SELECT * FROM system.runtime.nodes') rows = await cur.fetchall() await conn.close() ``` ### Response #### Success Response (200) - **rows** (list) - A list of rows returned by the query. #### Response Example ```json [ {"name": "node1", "state": "alive"} ] ``` ``` -------------------------------- ### Manage Transactions Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Enables transaction support by setting an isolation level, allowing for atomic operations. ```python import aiotrino from aiotrino import transaction async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='the-catalog', schema='the-schema', isolation_level=transaction.IsolationLevel.REPEATABLE_READ, ) as conn: cur = await conn.cursor() await cur.execute('INSERT INTO sometable VALUES (1, 2, 3)') await cur.fetchone() await cur.execute('INSERT INTO sometable VALUES (4, 5, 6)') await cur.fetchone() ``` -------------------------------- ### Transactions Source: https://github.com/mvanderlee/aiotrino/blob/main/README.md Manage transactions in Trino using the aiotrino client, including commit and rollback. ```APIDOC ## Transactions ### Description Enable and manage transactions in Trino. By default, the client operates in autocommit mode. Setting `isolation_level` to a value other than `IsolationLevel.AUTOCOMMIT` activates transaction mode. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters - **host** (string) - Required - The hostname or IP address of the Trino coordinator. - **port** (integer) - Required - The port number for the Trino coordinator. - **user** (string) - Required - The user principal. - **catalog** (string) - Required - The catalog to use. - **schema** (string) - Required - The schema to use. - **isolation_level** (enum) - Optional - The transaction isolation level. Set to a value other than `IsolationLevel.AUTOCOMMIT` to enable transactions. ### Request Example ```python import aiotrino from aiotrino import transaction async with aiotrino.dbapi.connect( host='localhost', port=8080, user='the-user', catalog='the-catalog', schema='the-schema', isolation_level=transaction.IsolationLevel.REPEATABLE_READ, ) as conn: cur = await conn.cursor() await cur.execute('INSERT INTO sometable VALUES (1, 2, 3)') await cur.fetchone() await cur.execute('INSERT INTO sometable VALUES (4, 5, 6)') await cur.fetchone() ``` ### Response #### Success Response (200) - **N/A** - Transactions are managed implicitly. Successful execution within the `with` block leads to a commit upon exit. Errors trigger a rollback. #### Response Example N/A ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.