### Install Trino Python Client Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Installs the Trino Python client using pip. This is the first step to using the client for database operations. ```bash pip install trino ``` -------------------------------- ### OAuth2 Authentication Setup with DBAPI Source: https://context7.com/trinodb/trino-python-client/llms.txt Illustrates the initial setup for connecting to Trino using OAuth2 authentication, which typically involves a browser-based interactive login flow. Requires specifying redirect handlers. ```python from trino.dbapi import connect from trino.auth import OAuth2Authentication, ConsoleRedirectHandler, WebBrowserRedirectHandler, CompositeRedirectHandler # Example setup - actual implementation depends on OAuth2 provider and redirect strategy # conn = connect( # host="trino.example.com", # port=443, # user="oauth_user", # auth=OAuth2Authentication( # redirect_handler=CompositeRedirectHandler([ # ConsoleRedirectHandler(), # WebBrowserRedirectHandler() # ]) # ), # http_scheme="https", # catalog="main", # schema="default" # ) # cur = conn.cursor() # cur.execute("SELECT 1") # print(cur.fetchone()) # cur.close() # conn.close() ``` -------------------------------- ### Install Trino Python Client with SQLAlchemy support Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Installs the Trino Python client with the necessary dependencies for SQLAlchemy integration. This allows using Trino with SQLAlchemy ORM and Core. ```bash pip install trino[sqlalchemy] ``` -------------------------------- ### Connect to Trino with OAuth2 Authentication Source: https://context7.com/trinodb/trino-python-client/llms.txt Demonstrates connecting to Trino using OAuth2 authentication, either directly in the URL or via connect_args. Requires appropriate OAuth2 setup. ```python from sqlalchemy import create_engine from trino.auth import OAuth2Authentication # OAuth2 authentication in URL engine = create_engine( "trino://user@trino.example.com:443/hive?externalAuthentication=true" ) # Or via connect_args engine = create_engine( "trino://user@trino.example.com:443/hive", connect_args={ "auth": OAuth2Authentication(), "http_scheme": "https", } ) ``` -------------------------------- ### SQLAlchemy Integration with Trino (Python) Source: https://context7.com/trinodb/trino-python-client/llms.txt Demonstrates integrating Trino with SQLAlchemy using both basic connection strings and the URL builder for complex configurations. Includes examples for executing raw SQL, table reflection, and cross-catalog queries. ```python # pip install trino[sqlalchemy] from sqlalchemy import create_engine, text, Table, MetaData, Column, Integer, String, select from sqlalchemy.orm import Session from trino.sqlalchemy import URL # Basic connection string engine = create_engine("trino://user@localhost:8080/hive/default") # Using URL builder for complex configurations engine = create_engine( URL( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", ) ) # With authentication and options engine = create_engine( "trino://admin:password@trino.example.com:443/hive/default", connect_args={ "http_scheme": "https", "session_properties": {"query_max_run_time": "1h"}, "client_tags": ["sqlalchemy", "etl"], "roles": {"hive": "analyst_role"}, } ) # Execute raw SQL with engine.connect() as conn: result = conn.execute(text("SELECT * FROM system.runtime.nodes")) for row in result: print(row) # Table reflection metadata = MetaData() users = Table("users", metadata, schema="default", autoload_with=engine) with engine.connect() as conn: stmt = select(users).where(users.c.active == True).limit(10) result = conn.execute(stmt) for row in result: print(row) # Cross-catalog queries orders = Table( "orders", metadata, Column("id", Integer), Column("customer_id", Integer), schema="warehouse", trino_catalog="iceberg", # Specify different catalog ) # Get catalog names from sqlalchemy import inspect inspector = inspect(engine) print("Catalogs:", inspector.get_catalog_names()) ``` -------------------------------- ### Trino to Python Type Mappings Source: https://context7.com/trinodb/trino-python-client/llms.txt Illustrates the mapping between Trino SQL data types and their corresponding Python types. Includes examples for basic types, complex types like arrays and maps, and interval types. ```python from trino.dbapi import connect from datetime import date, time, datetime, timedelta from dateutil.relativedelta import relativedelta from decimal import Decimal import uuid conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", ) cur = conn.cursor() # Type mapping examples cur.execute(""" SELECT true AS bool_val, -- bool CAST(42 AS TINYINT) AS tinyint_val, -- int CAST(1000 AS INTEGER) AS int_val, -- int CAST(9999999999 AS BIGINT) AS bigint_val, -- int CAST(3.14 AS REAL) AS real_val, -- float CAST(2.71828 AS DOUBLE) AS double_val, -- float CAST(123.45 AS DECIMAL(10,2)) AS decimal_val, -- Decimal 'hello' AS varchar_val, -- str DATE '2024-06-15' AS date_val, -- datetime.date TIME '14:30:00' AS time_val, -- datetime.time TIMESTAMP '2024-06-15 14:30:00' AS ts_val, -- datetime.datetime UUID '550e8400-e29b-41d4-a716-446655440000' AS uuid_val, -- uuid.UUID ARRAY[1, 2, 3] AS array_val, -- list MAP(ARRAY['a', 'b'], ARRAY[1, 2]) AS map_val, -- dict ROW(1, 'test', 3.14) AS row_val, -- tuple (with named access) X'48454C4C4F' AS binary_val, -- bytes INTERVAL '2' YEAR AS year_interval, -- relativedelta INTERVAL '30' DAY AS day_interval -- timedelta """) row = cur.fetchone() ``` -------------------------------- ### GSSAPI Authentication with SQLAlchemy Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Configure SQLAlchemy to connect to a Trino cluster using GSSAPI authentication. Ensure `trino[gssapi]` is installed. This approach leverages `requests-gssapi` for the underlying authentication mechanism. ```python from sqlalchemy import create_engine from trino.auth import GSSAPIAuthentication engine = create_engine( "trino://@:/", connect_args={ "auth": GSSAPIAuthentication(...), "http_scheme": "https", } ) ``` -------------------------------- ### Kerberos Authentication for Trino Python Client (DBAPI & SQLAlchemy) Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Connect to Trino using Kerberos authentication. Ensure Kerberos support is installed (`pip install trino[kerberos]`). This method is applicable for clusters configured with the Kerberos authentication type and works with both DBAPI and SQLAlchemy interfaces. ```python from trino.dbapi import connect from trino.auth import KerberosAuthentication conn = connect( user="", auth=KerberosAuthentication(...), http_scheme="https", ... ) ``` ```python from sqlalchemy import create_engine from trino.auth import KerberosAuthentication engine = create_engine( "trino://@:/", connect_args={ "auth": KerberosAuthentication(...), "http_scheme": "https", } ) ``` -------------------------------- ### Describe Query Output Columns with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Demonstrates how to use the `describe` method on a Trino Python client cursor to get metadata about the output columns of a query without executing the full query. This is useful for understanding query structure and data types. ```python from trino.dbapi import connect conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", ) cur = conn.cursor() # Describe what columns a query would return output_info = cur.describe(""" SELECT o.order_id, c.name AS customer_name, o.total_amount, o.created_at FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.status = 'completed' """) for col in output_info: print(f"Column: {col.name}") print(f" Type: {col.type}") print(f" Catalog: {col.catalog}") print(f" Schema: {col.schema}") print(f" Table: {col.table}") print(f" Aliased: {col.aliased}") print() cur.close() conn.close() ``` -------------------------------- ### OAuth2 Authentication with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Connect to Trino using OAuth2 authentication. This example shows both default browser-based redirection and a console-only handler. It also demonstrates executing a query and fetching results. ```python from trino.dbapi import connect from trino.auth import OAuth2Authentication, CompositeRedirectHandler, ConsoleRedirectHandler # Default: opens browser and prints URL to console conn = connect( host="trino.example.com", port=443, user="myuser", # Specify user for per-user token caching auth=OAuth2Authentication(), http_scheme="https", catalog="hive", schema="default", ) # Custom redirect handler (console only, no browser) conn_console = connect( host="trino.example.com", port=443, user="myuser", auth=OAuth2Authentication( redirect_auth_url_handler=CompositeRedirectHandler([ ConsoleRedirectHandler() ]) ), http_scheme="https", catalog="hive", schema="default", ) cur = conn.cursor() cur.execute("SELECT * FROM my_table LIMIT 10") results = cur.fetchall() cur.close() conn.close() ``` -------------------------------- ### GSSAPI Authentication with DBAPI Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Connect to a Trino cluster using GSSAPI authentication with the DBAPI interface. Requires `trino[gssapi]` to be installed. This method uses `requests-gssapi` for authentication. ```python from trino.dbapi import connect from trino.auth import GSSAPIAuthentication conn = connect( user="", auth=GSSAPIAuthentication(...), http_scheme="https", ... ) ``` -------------------------------- ### Certificate Authentication with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Connect to Trino using client certificate authentication for mTLS setups. This requires specifying the paths to the client certificate and private key. ```python from trino.dbapi import connect from trino.auth import CertificateAuthentication conn = connect( host="trino.example.com", port=443, user="service-account", auth=CertificateAuthentication( cert="/path/to/client-cert.pem", key="/path/to/client-key.pem" ), http_scheme="https", catalog="hive", schema="default", ) cur = conn.cursor() cur.execute("SELECT 1") print(cur.fetchone()) cur.close() conn.close() ``` -------------------------------- ### GSSAPI Authentication with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Connect to Trino using GSSAPI-based Kerberos authentication as an alternative to `requests-kerberos`. This requires installing `trino[gssapi]` and configuring GSSAPI parameters. ```python from trino.dbapi import connect from trino.auth import GSSAPIAuthentication # pip install trino[gssapi] conn = connect( host="trino.example.com", port=443, user="user@REALM.COM", auth=GSSAPIAuthentication( config="/etc/krb5.conf", service_name="HTTP", hostname_override="trino.example.com", principal="user@REALM.COM", ), http_scheme="https", catalog="hive", schema="default", ) cur = conn.cursor() cur.execute("SHOW SCHEMAS") schemas = cur.fetchall() print(schemas) cur.close() conn.close() ``` -------------------------------- ### SSL/TLS Configuration for Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Configure SSL verification and self-signed certificates for secure connections. Examples include disabling verification (not recommended), using a CA certificate for self-signed certificates, and providing a custom requests session with client certificates. ```python from trino.dbapi import connect from trino.auth import BasicAuthentication import requests # Disable SSL verification (not recommended for production) conn_no_verify = connect( host="trino.example.com", port=443, user="admin", auth=BasicAuthentication("admin", "password"), http_scheme="https", verify=False, # Disable SSL verification catalog="hive", schema="default", ) # Use self-signed certificate conn_self_signed = connect( host="trino.example.com", port=443, user="admin", auth=BasicAuthentication("admin", "password"), http_scheme="https", verify="/path/to/ca-certificate.crt", # Path to CA cert catalog="hive", schema="default", ) # Custom requests session with client certificate session = requests.Session() session.cert = "/path/to/client.pem" session.verify = "/path/to/ca-bundle.crt" conn_custom = connect( host="trino.example.com", port=443, user="admin", http_session=session, http_scheme="https", catalog="hive", schema="default", ) conn_no_verify.close() conn_self_signed.close() conn_custom.close() ``` -------------------------------- ### Kerberos Authentication with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Connect to Trino using Kerberos/SPNEGO authentication. This method is suitable for enterprise environments and requires the `trino[kerberos]` extra to be installed. Configuration includes Kerberos settings and service principal. ```python from trino.dbapi import connect from trino.auth import KerberosAuthentication # pip install trino[kerberos] conn = connect( host="trino.example.com", port=443, user="user@REALM.COM", auth=KerberosAuthentication( config="/etc/krb5.conf", service_name="trino", principal="user@REALM.COM", mutual_authentication=KerberosAuthentication.MUTUAL_REQUIRED, ca_bundle="/path/to/ca-bundle.crt", ), http_scheme="https", catalog="hive", schema="default", ) cur = conn.cursor() cur.execute("SELECT current_user") print(cur.fetchone()) cur.close() conn.close() ``` -------------------------------- ### Access ROW Type Elements by Index in Trino Source: https://context7.com/trinodb/trino-python-client/llms.txt Shows how to access elements within a Trino ROW type using positional indexing. This is useful when the schema of the ROW type is known or when direct access by index is preferred. The example retrieves a ROW value and then accesses its individual elements. ```python row_val = row[14] print(f"By index: {row_val[0]}, {row_val[1]}, {row_val[2]}") ``` -------------------------------- ### OAuth2 Authentication for Trino Python Client (DBAPI & SQLAlchemy) Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Connect to Trino using OAuth2 authentication. This method supports various redirect handlers and token caching mechanisms, including secure backend storage when keyring is installed. It's applicable for clusters configured with the OAuth2 authentication type. ```python from trino.dbapi import connect from trino.auth import OAuth2Authentication conn = connect( user="", auth=OAuth2Authentication(), http_scheme="https", ... ) ``` ```python from sqlalchemy import create_engine from trino.auth import OAuth2Authentication engine = create_engine( "trino://@:/", connect_args={ "auth": OAuth2Authentication(), "http_scheme": "https", } ) ``` -------------------------------- ### Connect and Query Trino using SQLAlchemy Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Shows how to connect to Trino using SQLAlchemy and execute a query. It demonstrates creating an engine with a connection string and fetching results. ```python from sqlalchemy import create_engine from sqlalchemy.schema import Table, MetaData from sqlalchemy.sql.expression import select, text engine = create_engine('trino://user@localhost:8080/system') connection = engine.connect() rows = connection.execute(text("SELECT * FROM runtime.nodes")).fetchall() # or using SQLAlchemy schema nodes = Table( 'nodes', MetaData(schema='runtime'), autoload=True, autoload_with=engine ) rows = connection.execute(select(nodes)).fetchall() ``` -------------------------------- ### Connect and Query Trino using DBAPI Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Demonstrates how to connect to a Trino cluster and execute a SQL query using the DBAPI interface. It shows how to establish a connection and fetch all results from a query. ```python from trino.dbapi import connect conn = connect( host="", port=, user="", catalog="", schema="", ) cur = conn.cursor() cur.execute("SELECT * FROM system.runtime.nodes") rows = cur.fetchall() ``` -------------------------------- ### Connect to Trino with Certificate Authentication Source: https://context7.com/trinodb/trino-python-client/llms.txt Shows how to connect to Trino using client certificate authentication. Requires specifying the paths to the certificate and key files. ```python from sqlalchemy import create_engine engine = create_engine( "trino://user@trino.example.com:443/hive?cert=/path/cert.pem&key=/path/key.pem" ) ``` -------------------------------- ### Configure SQLAlchemy Engine with Trino Connection Arguments Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Illustrates how to create a SQLAlchemy engine for Trino, passing additional connection arguments like session properties, client tags, and roles. This allows for fine-grained control over the Trino connection. ```python from sqlalchemy import create_engine from trino.sqlalchemy import URL engine = create_engine( URL( host="localhost", port=8080, catalog="system" ), connect_args={ "session_properties": {'query_max_run_time': '1d'}, "client_tags": ["tag1", "tag2"], "roles": {"catalog1": "role1"}, } ) # or in connection string engine = create_engine( 'trino://user@localhost:8080/system?' 'session_properties={"query_max_run_time": "1d"}' '&client_tags=["tag1", "tag2"]' '&roles={"catalog1": "role1"}' ) # or using the URL factory method engine = create_engine(URL( host="localhost", port=8080, client_tags=["tag1", "tag2"] )) ``` -------------------------------- ### Use Context Managers for Trino Connections and Cursors (Python) Source: https://context7.com/trinodb/trino-python-client/llms.txt Illustrates using context managers (`with` statement) for Trino connections and cursors to ensure automatic resource cleanup. Also shows method chaining for execute and fetchall. ```python from trino.dbapi import connect # Connection context manager with connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", ) as conn: # Cursor context manager with conn.cursor() as cur: cur.execute("SELECT * FROM users LIMIT 10") for row in cur: print(row) # Cursor automatically closed # Connection automatically closed # Method chaining with connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", ) as conn: with conn.cursor() as cur: # Execute returns cursor for chaining results = cur.execute("SELECT id, name FROM users").fetchall() print(results) ``` -------------------------------- ### Connect to Trino using Basic Authentication (SQLAlchemy) Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Shows how to configure a SQLAlchemy engine to connect to Trino using basic authentication. This can be done directly in the connection string or via the `connect_args` parameter. ```python from sqlalchemy import create_engine from trino.auth import BasicAuthentication engine = create_engine("trino://:@:/") # or as connect_args engine = create_engine( "trino://@:/", connect_args={ "auth": BasicAuthentication("", ""), "http_scheme": "https", } ) ``` -------------------------------- ### Connect to Trino with Compression and Segment Cursors (Python) Source: https://context7.com/trinodb/trino-python-client/llms.txt Demonstrates connecting to Trino with specified compression encoding order and using a segment cursor for advanced spooling control. Results are automatically decompressed. ```python from trino.dbapi import connect # Specify preference order for compression conn_multi = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", encoding=["json+zstd", "json+lz4", "json"], # Fallback order ) cur = conn_multi.cursor() cur.execute("SELECT * FROM very_large_table") # Results are automatically decompressed for row in cur: process_row(row) # Segment cursor for advanced spooling control seg_cur = conn_multi.cursor(cursor_style="segment") seg_cur.execute("SELECT * FROM large_dataset") for segment in seg_cur: # Each segment contains a batch of rows print(f"Segment encoding: {segment.encoding}") print(f"Segment metadata: {segment.metadata}") cur.close() conn_multi.close() ``` -------------------------------- ### Configure Roles and Extra Credentials with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Demonstrates how to configure authorization roles per catalog and provide extra credentials for Trino connectors using the trino.dbapi.connect function. This allows for fine-grained access control and authentication for different data sources. ```python from trino.dbapi import connect # Set roles per catalog conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", roles={ "hive": "analyst_role", "iceberg": "reader_role", "system": "admin", }, ) # System role shorthand conn_system = connect( host="localhost", port=8080, user="admin", catalog="hive", schema="default", roles="admin_role", # Equivalent to {"system": "admin_role"} ) # Extra credentials for connectors conn_extra = connect( host="localhost", port=8080, user="etl_user", catalog="hive", schema="default", extra_credential=[ ("hive.metastore.username", "hive_user"), ("hive.metastore.password", "secret"), ], ) conn.close() conn_system.close() conn_extra.close() ``` -------------------------------- ### Connect to Trino using Basic Authentication (DBAPI) Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Demonstrates how to establish a DBAPI connection to Trino using basic authentication. This method is suitable for Trino clusters configured with password file, LDAP, or Salesforce authentication. ```python from trino.dbapi import connect from trino.auth import BasicAuthentication conn = connect( user="", auth=BasicAuthentication("", ""), http_scheme="https", ... ) ``` -------------------------------- ### Parameterized Queries with DBAPI Source: https://context7.com/trinodb/trino-python-client/llms.txt Shows how to execute SQL queries with parameters using prepared statements in Trino via the DBAPI interface. Supports various data types and batch operations like executemany. ```python from trino.dbapi import connect from datetime import date, datetime from decimal import Decimal import uuid conn = connect( host="localhost", port=8080, user="admin", catalog="hive", schema="default", ) cur = conn.cursor() # Query with parameters (uses EXECUTE IMMEDIATE by default) cur.execute( "SELECT * FROM orders WHERE customer_id = ? AND order_date > ?", [12345, date(2024, 1, 1)] ) orders = cur.fetchall() # Multiple parameter types supported cur.execute( """ INSERT INTO analytics.events ( event_id, event_time, amount, tags, metadata, user_uuid ) VALUES (?, ?, ?, ?, ?, ?) """, [ 1001, datetime(2024, 6, 15, 10, 30, 0), Decimal("199.99"), ["purchase", "electronics"], # ARRAY {"source": "web", "campaign": "summer"}, # MAP uuid.UUID("550e8400-e29b-41d4-a716-446655440000") ] ) # Execute many - batch insert data = [ (1, "Alice", "alice@example.com"), (2, "Bob", "bob@example.com"), (3, "Charlie", "charlie@example.com"), ] cur.executemany( "INSERT INTO users (id, name, email) VALUES (?, ?, ?)", data ) # Force legacy prepared statements if needed conn_legacy = connect( host="localhost", port=8080, user="admin", catalog="hive", schema="default", legacy_prepared_statements=True, ) cur.close() conn.close() ``` -------------------------------- ### Enable Spooling Protocol with Compression in Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Explains how to enable the spooling protocol with compression for efficient handling of large result sets when using the Trino Python client. This requires server-side support and can be configured using the `encoding` parameter. ```python from trino.dbapi import connect # Enable spooling with compression (requires Trino server support) conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", encoding="json+zstd", # Options: "json", "json+lz4", "json+zstd" ) ``` -------------------------------- ### Handle Trino Exceptions in Python Source: https://context7.com/trinodb/trino-python-client/llms.txt Demonstrates comprehensive error handling for various Trino-specific exceptions using a try-except block. Covers user, external, connection, auth, data, and general Trino errors. ```python from trino.dbapi import connect from trino.exceptions import ( Error, DatabaseError, OperationalError, ProgrammingError, TrinoQueryError, TrinoUserError, TrinoExternalError, TrinoConnectionError, TrinoAuthError, TrinoDataError, NotSupportedError, ) conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", ) cur = conn.cursor() try: cur.execute("SELECT * FROM nonexistent_table") cur.fetchall() except TrinoUserError as e: # User error (syntax error, table not found, etc.) 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: print(f"Location: line {e.error_location[0]}, column {e.error_location[1]}") except TrinoExternalError as e: # External error (connector issues, network problems) print(f"External error: {e.message}") except TrinoConnectionError as e: # Connection failed print(f"Connection error: {e}") except TrinoAuthError as e: # Authentication failed print(f"Auth error: {e}") except TrinoDataError as e: # Data type conversion error print(f"Data error: {e}") except NotSupportedError as e: # Feature not supported print(f"Not supported: {e}") except OperationalError as e: # General operational error print(f"Operational error: {e}") except ProgrammingError as e: # Programming error print(f"Programming error: {e}") except DatabaseError as e: # Database error print(f"Database error: {e}") except Error as e: # Any Trino error print(f"Error: {e}") finally: cur.close() conn.close() ``` -------------------------------- ### Connect to Trino with Legacy Primitive Types (Python) Source: https://context7.com/trinodb/trino-python-client/llms.txt Shows how to connect to Trino and disable automatic type conversion to receive raw string values, useful for types like dates that may not have direct Python equivalents. ```python from trino.dbapi import connect # Enable legacy mode for raw values conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", legacy_primitive_types=True, ) cur = conn.cursor() # Negative dates not representable in Python datetime cur.execute("SELECT DATE '-2001-08-22'") row = cur.fetchone() print(f"Date as string: {row[0]}") # "-2001-08-22" print(f"Type code: {cur.description[0].type_code}") # "date" # Can also set per-cursor cur_typed = conn.cursor(legacy_primitive_types=False) cur_typed.execute("SELECT DATE '2024-01-15'") row = cur_typed.fetchone() print(f"Date as datetime.date: {row[0]}") # datetime.date(2024, 1, 15) cur.close() conn.close() ``` -------------------------------- ### Basic Authentication with DBAPI Source: https://context7.com/trinodb/trino-python-client/llms.txt Connects to Trino using Basic Authentication, suitable for username/password credentials like LDAP or password files. Requires specifying host, port, user, and authentication details. ```python from trino.dbapi import connect from trino.auth import BasicAuthentication conn = connect( host="trino.example.com", port=443, user="myuser", auth=BasicAuthentication("myuser", "mypassword"), http_scheme="https", catalog="hive", schema="default", ) cur = conn.cursor() cur.execute("SELECT current_user") print(cur.fetchone()) cur.close() conn.close() ``` -------------------------------- ### SQLAlchemy with Authentication Methods for Trino (Python) Source: https://context7.com/trinodb/trino-python-client/llms.txt Details various authentication methods for SQLAlchemy connections to Trino, including basic authentication (in URL and via connect_args), JWT, and OAuth2. ```python from sqlalchemy import create_engine from trino.auth import BasicAuthentication, JWTAuthentication, OAuth2Authentication from trino.sqlalchemy import URL # Basic auth in URL engine = create_engine("trino://user:password@trino.example.com:443/hive") # Basic auth via connect_args engine = create_engine( "trino://user@trino.example.com:443/hive", connect_args={ "auth": BasicAuthentication("user", "password"), "http_scheme": "https", } ) # JWT authentication engine = create_engine( "trino://service@trino.example.com:443/hive?access_token=eyJhbGc..." ) ``` -------------------------------- ### Using Self-Signed Certificates Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Configure SSL to use self-signed certificates by providing the path to the certificate file in the `verify` parameter. Refer to the Python requests library documentation for advanced SSL options. ```python from trino.dbapi import connect from trino.auth import BasicAuthentication conn = connect( user="", auth=BasicAuthentication("", ""), http_scheme="https", verify="/path/to/cert.crt" ) ``` -------------------------------- ### Enable Transactions with Trino Python Client Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Demonstrates how to enable and manage transactions in the Trino Python client by setting the isolation level. Transactions are automatically committed or rolled back upon exiting the 'with' context. ```python from trino.dbapi import connect from trino.transaction import IsolationLevel with connect( isolation_level=IsolationLevel.REPEATABLE_READ, ... ) as conn: cur = conn.cursor() cur.execute('INSERT INTO sometable VALUES (1, 2, 3)') cur.fetchall() cur.execute('INSERT INTO sometable VALUES (4, 5, 6)') cur.fetchall() ``` -------------------------------- ### Manage Transactions with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Illustrates how to use transactions with the Trino Python client, including autocommit mode, using a context manager for automatic commit/rollback, and manual transaction control with explicit commit and rollback operations. Supports various isolation levels. ```python from trino.dbapi import connect from trino.transaction import IsolationLevel # Autocommit mode (default) conn_auto = connect( host="localhost", port=8080, user="admin", catalog="hive", schema="default", isolation_level=IsolationLevel.AUTOCOMMIT, ) # Transaction with context manager with connect( host="localhost", port=8080, user="admin", catalog="iceberg", schema="warehouse", isolation_level=IsolationLevel.READ_COMMITTED, ) as conn: cur = conn.cursor() # All operations in transaction cur.execute("INSERT INTO orders VALUES (1, 'pending', 100.00)") cur.fetchall() cur.execute("UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 1") cur.fetchall() cur.execute("INSERT INTO order_history VALUES (1, CURRENT_TIMESTAMP)") cur.fetchall() # Commits automatically on successful exit # Manual transaction control conn = connect( host="localhost", port=8080, user="admin", catalog="iceberg", schema="warehouse", isolation_level=IsolationLevel.REPEATABLE_READ, ) try: cur = conn.cursor() cur.execute("INSERT INTO audit_log VALUES (CURRENT_TIMESTAMP, 'start')") cur.fetchall() # Simulate an error condition cur.execute("SELECT * FROM critical_table") if not cur.fetchall(): raise ValueError("Critical data missing") conn.commit() except Exception as e: conn.rollback() print(f"Transaction rolled back: {e}") finally: conn.close() ``` -------------------------------- ### Enabling Spooled Protocol with Multiple Encodings Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Enable the Trino client spooling protocol by providing a list of supported encodings in order of preference. The client will attempt to use the first available encoding. Requires server-side support. ```python from trino.dbapi import connect conn = connect( encoding=["json+zstd", "json"] ) ``` -------------------------------- ### Connect to Trino with Session Properties in URL Source: https://context7.com/trinodb/trino-python-client/llms.txt Connects to Trino and sets session properties, client tags, and roles directly within the connection URL. Properties are JSON encoded. ```python from sqlalchemy import create_engine engine = create_engine( 'trino://user@localhost:8080/hive?' 'session_properties={"query_max_run_time": "1h"}' '&client_tags=["etl", "batch"]' '&roles={"hive": "admin"}' ) ``` -------------------------------- ### Certificate Authentication for Trino Python Client (DBAPI & SQLAlchemy) Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Connect to Trino using certificate-based authentication. This method requires paths to a valid client certificate and private key. It's compatible with both DBAPI and SQLAlchemy interfaces for secure client authentication. ```python from trino.dbapi import connect from trino.auth import CertificateAuthentication conn = connect( user="", auth=CertificateAuthentication("/path/to/cert.pem", "/path/to/key.pem"), http_scheme="https", ... ) ``` ```python from sqlalchemy import create_engine from trino.auth import CertificateAuthentication engine = create_engine("trino://@://?cert=&key=") # or as connect_args engine = create_engine( "trino://@:/", connect_args={ "auth": CertificateAuthentication("/path/to/cert.pem", "/path/to/key.pem"), "http_scheme": "https", } ) ``` -------------------------------- ### Setting Authorization Roles Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Specify authorization roles for Trino catalogs using the `roles` parameter. This can be a dictionary mapping catalog names to roles, or a single string for the system role. ```python import trino conn = trino.dbapi.connect( host='localhost', port=443, user='the-user', roles={"catalog1": "roleA", "catalog2": "roleB"}, ) ``` ```python import trino conn = trino.dbapi.connect( host='localhost', port=443, user='the-user', roles="role1" # equivalent to {"system": "role1"} ) ``` -------------------------------- ### Configure Custom HTTP Session for Trino Python Client Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Shows how to pass a custom requests.Session object to the Trino Python client. This allows for advanced configurations like setting custom HTTP headers or client certificates. ```python import requests from trino.dbapi import connect s = requests.Session() s.cert = '/path/client.cert' conn = connect( http_session=s, ... ) ``` -------------------------------- ### Connect to Trino with JWT Authentication Source: https://context7.com/trinodb/trino-python-client/llms.txt Establishes a connection to Trino using JWT for authentication. Requires the JWT token and specifies the HTTP scheme. ```python from sqlalchemy import create_engine from trino.auth import JWTAuthentication engine = create_engine( "trino://service@trino.example.com:443/hive", connect_args={ "auth": JWTAuthentication("eyJhbGc..."), "http_scheme": "https", } ) ``` -------------------------------- ### Cancel a Running Trino Query in Python Source: https://context7.com/trinodb/trino-python-client/llms.txt Shows how to execute a query and then cancel it if it's taking too long. Ensures resources are cleaned up by closing the cursor and connection. ```python from trino.dbapi import connect conn = connect(host="localhost", port=8080, user="analyst", catalog="hive", schema="default") cur = conn.cursor() try: cur.execute("SELECT * FROM very_large_table") # Cancel if taking too long cur.cancel() except Exception as e: print(f"Query cancelled or failed: {e}") finally: cur.close() conn.close() ``` -------------------------------- ### Session Properties and Timezone with Trino Python Client Source: https://context7.com/trinodb/trino-python-client/llms.txt Configure session-level properties and timezone for query execution. This includes setting query tuning parameters, specifying a timezone, and adding client tags for tracking. ```python from trino.dbapi import connect conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", # Session properties for query tuning session_properties={ "query_max_run_time": "1h", "query_max_memory": "4GB", "optimize_hash_generation": "true", }, # Set timezone (defaults to local timezone) timezone="America/New_York", # Client tags for tracking client_tags=["analytics", "report-generation"], ) cur = conn.cursor() # Query uses configured timezone cur.execute("SELECT current_timestamp, current_timezone()") print(cur.fetchone()) # View query info cur.execute("SELECT * FROM large_table LIMIT 100") print(f"Query ID: {cur.query_id}") print(f"Info URI: {cur.info_uri}") print(f"Stats: {cur.stats}") cur.close() conn.close() ``` -------------------------------- ### Access Trino Data with Proper Python Types Source: https://context7.com/trinodb/trino-python-client/llms.txt Demonstrates how to assert the correct Python data types when accessing columns from a Trino query result. This is crucial for ensuring data integrity and correct processing in your application. It covers a wide range of Trino data types and their corresponding Python representations. ```python assert isinstance(row[0], bool) assert isinstance(row[4], float) assert isinstance(row[6], Decimal) assert isinstance(row[8], date) assert isinstance(row[9], time) assert isinstance(row[10], datetime) assert isinstance(row[11], uuid.UUID) assert isinstance(row[12], list) assert isinstance(row[13], dict) assert isinstance(row[14], tuple) assert isinstance(row[15], bytes) assert isinstance(row[16], relativedelta) assert isinstance(row[17], timedelta) ``` -------------------------------- ### JWT Authentication with DBAPI Source: https://context7.com/trinodb/trino-python-client/llms.txt Establishes a connection to Trino using JSON Web Token (JWT) authentication for secure, token-based identity verification. Requires a pre-obtained JWT token. ```python from trino.dbapi import connect from trino.auth import JWTAuthentication # Obtain JWT token from your identity provider jwt_token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." conn = connect( host="trino.example.com", port=443, user="service-account", auth=JWTAuthentication(jwt_token), http_scheme="https", catalog="iceberg", schema="analytics", ) cur = conn.cursor() cur.execute("SHOW CATALOGS") catalogs = cur.fetchall() print("Available catalogs:", catalogs) cur.close() conn.close() ``` -------------------------------- ### Enabling Spooled Protocol with Single Encoding Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Enable the Trino client spooling protocol by specifying a supported encoding in the `encoding` parameter. Supported encodings include `json`, `json+lz4`, and `json+zstd`. Requires server-side support. ```python from trino.dbapi import connect conn = connect( encoding="json+zstd" ) ``` -------------------------------- ### Access Query Metadata with Trino Python Client Cursor Source: https://context7.com/trinodb/trino-python-client/llms.txt Shows how to retrieve query metadata, including column descriptions, query ID, text, URI, row count, update type, statistics, and warnings, using cursor properties after executing a query with the Trino Python client. ```python from trino.dbapi import connect conn = connect( host="localhost", port=8080, user="analyst", catalog="hive", schema="default", ) cur = conn.cursor() cur.execute("SELECT id, name, created_at, amount FROM sales WHERE year = 2024") # Column description (name, type_code, display_size, internal_size, precision, scale, null_ok) print("Columns:") for col in cur.description: print(f" {col.name}: {col.type_code} (precision={col.precision}, scale={col.scale})") # Query properties print(f"Query ID: {cur.query_id}") print(f"Query text: {cur.query}") print(f"Info URI: {cur.info_uri}") # Fetch results rows = cur.fetchall() # Row count for DML statements cur.execute("INSERT INTO archive SELECT * FROM sales WHERE year < 2020") cur.fetchall() print(f"Rows affected: {cur.rowcount}") # Update type print(f"Update type: {cur.update_type}") # Query statistics print(f"Stats: {cur.stats}") # Warnings if cur.warnings: for warning in cur.warnings: print(f"Warning: {warning}") cur.close() conn.close() ``` -------------------------------- ### Disabling SSL Verification Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Disable SSL certificate verification by setting the `verify` parameter to `False`. This is useful for testing or when dealing with self-signed certificates, but reduces security. ```python from trino.dbapi import connect from trino.auth import BasicAuthentication conn = connect( user="", auth=BasicAuthentication("", ""), http_scheme="https", verify=False ) ``` -------------------------------- ### Sending Extra Credentials Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Send additional credentials to the Trino server using the `extra_credential` parameter. This is useful for custom authentication schemes or passing specific headers. The credentials are provided as a list of tuples. ```python import trino conn = trino.dbapi.connect( host='localhost', port=443, user='the-user', extra_credential=[('a.username', 'bar'), ('a.password', 'foo')], ) cur = conn.cursor() cur.execute('SELECT * FROM system.runtime.nodes') rows = cur.fetchall() ``` -------------------------------- ### JWT Authentication for Trino Python Client (DBAPI & SQLAlchemy) Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Connect to Trino using JWT authentication. This method is suitable for clusters configured with the JWT authentication type. It supports both the DBAPI and SQLAlchemy interfaces, requiring a JWT token for authorization. ```python from trino.dbapi import connect from trino.auth import JWTAuthentication conn = connect( user="", auth=JWTAuthentication(""), http_scheme="https", ... ) ``` ```python from sqlalchemy import create_engine engine = create_engine("trino://@://?access_token=") # or as connect_args from trino.auth import JWTAuthentication engine = create_engine( "trino://@:/", connect_args={ "auth": JWTAuthentication(""), "http_scheme": "https", } ) ``` -------------------------------- ### Setting Session Timezone Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Explicitly set the session timezone using an IANA time zone name. If not specified, the timezone defaults to the client's local timezone. To maintain pre-0.320.0 behavior (UTC), pass `timezone='UTC'`. ```python import trino conn = trino.dbapi.connect( host='localhost', port=443, user='username', timezone='Europe/Brussels', ) ``` -------------------------------- ### Close Trino Database Connections Source: https://context7.com/trinodb/trino-python-client/llms.txt Illustrates the proper way to close Trino database connections using the DBAPI interface. It is essential to close connections to release resources and prevent potential issues. This snippet shows the standard `close()` method calls for both the cursor and the connection. ```python cur.close() conn.close() ``` -------------------------------- ### Disable Legacy Primitive Type Conversion in Trino Python Client Source: https://github.com/trinodb/trino-python-client/blob/master/README.md Illustrates how to disable the default conversion of Trino data types to corresponding Python types by setting `legacy_primitive_types` to True. This is useful for handling types like DATE that have limitations in Python representation. ```python import trino conn = trino.dbapi.connect( legacy_primitive_types=True, ... ) cur = conn.cursor() # Negative DATE cannot be represented with Python types # legacy_primitive_types needs to be enabled cur.execute("SELECT DATE '-2001-08-22'") rows = cur.fetchall() assert rows[0][0] == "-2001-08-22" assert cur.description[0][1] == "date" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.