Client for the Trino distributed SQL Engine with DB-API 2.0 support, low-level client interface, and SQLAlchemy dialect.
npx @tessl/cli install tessl/pypi-trino@0.336.0A comprehensive Python client library for Trino (formerly PrestoSQL), a distributed SQL query engine designed for interactive and batch big data processing. The client provides multiple interfaces including a low-level client for direct communication with Trino clusters, a DB-API 2.0 compliant interface for standard database connectivity, and a SQLAlchemy dialect for ORM integration.
pip install trinopip install trino[sqlalchemy] (SQLAlchemy support), pip install trino[kerberos] (Kerberos auth), pip install trino[gssapi] (GSSAPI auth)import trinoFor DB-API 2.0 interface:
from trino.dbapi import connectFor low-level client:
from trino.client import TrinoRequest, TrinoQuery, ClientSessionFor authentication:
from trino.auth import BasicAuthentication, JWTAuthentication, OAuth2AuthenticationFor SQLAlchemy:
from sqlalchemy import create_engineFor constants and logging:
from trino import constants, loggingfrom trino.dbapi import connect
# Connect to Trino
conn = connect(
host="localhost",
port=8080,
user="testuser",
catalog="memory",
schema="default"
)
# Execute queries
cur = conn.cursor()
cur.execute("SELECT * FROM system.runtime.nodes")
rows = cur.fetchall()
# Close connection
conn.close()from sqlalchemy import create_engine, text
# Create engine
engine = create_engine('trino://user@localhost:8080/system')
# Execute queries
with engine.connect() as connection:
result = connection.execute(text("SELECT * FROM runtime.nodes"))
rows = result.fetchall()The Trino Python client is built with a layered architecture:
trino.dbapi) providing Connection and Cursor objectstrino.client) with TrinoRequest, TrinoQuery, and ClientSessiontrino.auth) supporting Basic, JWT, OAuth2, Kerberos, GSSAPI, and Certificate authenticationtrino.sqlalchemy) for ORM and SQL expression language supporttrino.types) with precision handlingtrino.transaction) with isolation levelsStandards-compliant database connectivity with Connection and Cursor objects, transaction support, prepared statements, and comprehensive error handling following PEP 249.
def connect(
host: str,
port: int = None,
user: str = None,
source: str = "trino-python-client",
catalog: str = None,
schema: str = None,
**kwargs
) -> Connectionclass Connection:
def cursor(self, cursor_style: str = "row", legacy_primitive_types: bool = None) -> Cursor
def commit(self) -> None
def rollback(self) -> None
def close(self) -> None
class Cursor:
def execute(self, operation: str, params: list = None) -> Cursor
def executemany(self, operation: str, seq_of_params: list) -> Cursor
def fetchone(self) -> Optional[List[Any]]
def fetchmany(self, size: int = None) -> List[List[Any]]
def fetchall(self) -> List[List[Any]]
def describe(self, sql: str) -> List[DescribeOutput]Direct HTTP protocol implementation providing fine-grained control over query execution, session management, and result handling with support for the spooled protocol.
class TrinoRequest:
def __init__(
self,
host: str,
port: int,
client_session: ClientSession,
http_session: Optional[Session] = None,
**kwargs
)
def post(self, sql: str, additional_http_headers: Optional[Dict[str, Any]] = None) -> Response
def get(self, url: str) -> Response
class TrinoQuery:
def __init__(self, request: TrinoRequest, query: str, **kwargs)
def execute(self, additional_http_headers: dict = None) -> TrinoResult
def fetch(self) -> List[Union[List[Any]], Any]
def cancel(self) -> NoneComprehensive authentication support including Basic, JWT, OAuth2, Kerberos, GSSAPI, and client certificate authentication with configurable redirect handlers and token caching.
class BasicAuthentication:
def __init__(self, username: str, password: str)
class JWTAuthentication:
def __init__(self, token: str)
class OAuth2Authentication:
def __init__(self, redirect_auth_url_handler: CompositeRedirectHandler = ...)
class KerberosAuthentication:
def __init__(
self,
config: Optional[str] = None,
service_name: Optional[str] = None,
mutual_authentication: int = MUTUAL_REQUIRED,
**kwargs
)SQLAlchemy dialect implementation enabling ORM usage, connection pooling, and SQL expression language support with Trino-specific type mappings and query compilation.
from trino.sqlalchemy import URL
def create_engine(url: str, **kwargs) -> EngineDefault values, HTTP headers, and protocol constants used throughout the client library for configuration and HTTP communication with Trino coordinators.
# Connection defaults
DEFAULT_PORT: int = 8080
DEFAULT_TLS_PORT: int = 443
DEFAULT_SOURCE: str = "trino-python-client"
DEFAULT_CATALOG: Optional[str] = None
DEFAULT_SCHEMA: Optional[str] = None
DEFAULT_AUTH: Optional[Any] = None
DEFAULT_MAX_ATTEMPTS: int = 3
DEFAULT_REQUEST_TIMEOUT: float = 30.0
# Protocol constants
HTTP: str = "http"
HTTPS: str = "https"
URL_STATEMENT_PATH: str = "/v1/statement"
CLIENT_NAME: str = "Trino Python Client"
# HTTP headers
HEADER_CATALOG: str = "X-Trino-Catalog"
HEADER_SCHEMA: str = "X-Trino-Schema"
HEADER_SOURCE: str = "X-Trino-Source"
HEADER_USER: str = "X-Trino-User"
HEADER_SESSION: str = "X-Trino-Session"
HEADER_TRANSACTION: str = "X-Trino-Transaction-Id"
HEADER_CLIENT_TAGS: str = "X-Trino-Client-Tags"
HEADER_TIMEZONE: str = "X-Trino-Time-Zone"
# Type classifications
LENGTH_TYPES: List[str] = ["char", "varchar"]
PRECISION_TYPES: List[str] = ["time", "time with time zone", "timestamp", "timestamp with time zone", "decimal"]
SCALE_TYPES: List[str] = ["decimal"]Logging utilities for configuring and managing Trino client logging with proper level control and logger hierarchy.
def get_logger(name: str, log_level: Optional[int] = None) -> logging.Logger
"""
Create or retrieve logger with optional level configuration.
Parameters:
- name: Logger name (typically __name__)
- log_level: Optional logging level override
Returns:
Configured logger instance
"""
# Module constants
LEVEL: int = logging.INFO
trino_root_logger: logging.Logger # Root logger for trino package# Isolation levels for transactions
class IsolationLevel(Enum):
AUTOCOMMIT = 0
READ_UNCOMMITTED = 1
READ_COMMITTED = 2
REPEATABLE_READ = 3
SERIALIZABLE = 4
# Enhanced temporal types with precision handling
class TemporalType(Generic[PythonTemporalType]):
def round_to(self, precision: int) -> TemporalType[PythonTemporalType]
def to_python_type(self) -> PythonTemporalType
class Time(TemporalType[time])
class TimeWithTimeZone(Time)
class Timestamp(TemporalType[datetime])
class TimestampWithTimeZone(Timestamp)
# Named tuple with attribute access for row results
class NamedRowTuple(Tuple[Any, ...]):
def __init__(self, values: List[Any], names: List[str], types: List[str])# DB-API 2.0 exceptions (PEP 249)
class Error(Exception)
class Warning(Exception)
class InterfaceError(Error)
class DatabaseError(Error)
class InternalError(DatabaseError)
class OperationalError(DatabaseError)
class ProgrammingError(DatabaseError)
class IntegrityError(DatabaseError)
class DataError(DatabaseError)
class NotSupportedError(DatabaseError)
# Trino-specific exceptions
class TrinoQueryError(Error):
@property
def error_code(self) -> Optional[int]
@property
def error_name(self) -> Optional[str]
@property
def message(self) -> str
@property
def query_id(self) -> Optional[str]
class TrinoExternalError(TrinoQueryError, OperationalError)
class TrinoInternalError(TrinoQueryError, InternalError)
class TrinoUserError(TrinoQueryError, ProgrammingError)
class TrinoAuthError(OperationalError)
class TrinoConnectionError(OperationalError)
class TrinoDataError(NotSupportedError)
# HTTP exceptions
class HttpError(Exception)
class Http502Error(HttpError)
class Http503Error(HttpError)
class Http504Error(HttpError)