or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-trino

Client for the Trino distributed SQL Engine with DB-API 2.0 support, low-level client interface, and SQLAlchemy dialect.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/trino@0.336.x

To install, run

npx @tessl/cli install tessl/pypi-trino@0.336.0

0

# Trino Python Client

1

2

A 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.

3

4

## Package Information

5

6

- **Package Name**: trino

7

- **Language**: Python

8

- **Installation**: `pip install trino`

9

- **Extras**: `pip install trino[sqlalchemy]` (SQLAlchemy support), `pip install trino[kerberos]` (Kerberos auth), `pip install trino[gssapi]` (GSSAPI auth)

10

11

## Core Imports

12

13

```python

14

import trino

15

```

16

17

For DB-API 2.0 interface:

18

19

```python

20

from trino.dbapi import connect

21

```

22

23

For low-level client:

24

25

```python

26

from trino.client import TrinoRequest, TrinoQuery, ClientSession

27

```

28

29

For authentication:

30

31

```python

32

from trino.auth import BasicAuthentication, JWTAuthentication, OAuth2Authentication

33

```

34

35

For SQLAlchemy:

36

37

```python

38

from sqlalchemy import create_engine

39

```

40

41

For constants and logging:

42

43

```python

44

from trino import constants, logging

45

```

46

47

## Basic Usage

48

49

### DB-API 2.0 Interface (Recommended)

50

51

```python

52

from trino.dbapi import connect

53

54

# Connect to Trino

55

conn = connect(

56

host="localhost",

57

port=8080,

58

user="testuser",

59

catalog="memory",

60

schema="default"

61

)

62

63

# Execute queries

64

cur = conn.cursor()

65

cur.execute("SELECT * FROM system.runtime.nodes")

66

rows = cur.fetchall()

67

68

# Close connection

69

conn.close()

70

```

71

72

### SQLAlchemy Interface

73

74

```python

75

from sqlalchemy import create_engine, text

76

77

# Create engine

78

engine = create_engine('trino://user@localhost:8080/system')

79

80

# Execute queries

81

with engine.connect() as connection:

82

result = connection.execute(text("SELECT * FROM runtime.nodes"))

83

rows = result.fetchall()

84

```

85

86

## Architecture

87

88

The Trino Python client is built with a layered architecture:

89

90

- **DB-API 2.0 Layer**: Standards-compliant interface (`trino.dbapi`) providing Connection and Cursor objects

91

- **Low-Level Client Layer**: Core HTTP protocol implementation (`trino.client`) with TrinoRequest, TrinoQuery, and ClientSession

92

- **Authentication Layer**: Pluggable authentication mechanisms (`trino.auth`) supporting Basic, JWT, OAuth2, Kerberos, GSSAPI, and Certificate authentication

93

- **SQLAlchemy Integration**: Dialect implementation (`trino.sqlalchemy`) for ORM and SQL expression language support

94

- **Type System**: Enhanced temporal types and row representations (`trino.types`) with precision handling

95

- **Transaction Support**: Transaction management (`trino.transaction`) with isolation levels

96

97

## Capabilities

98

99

### DB-API 2.0 Interface

100

101

Standards-compliant database connectivity with Connection and Cursor objects, transaction support, prepared statements, and comprehensive error handling following PEP 249.

102

103

```python { .api }

104

def connect(

105

host: str,

106

port: int = None,

107

user: str = None,

108

source: str = "trino-python-client",

109

catalog: str = None,

110

schema: str = None,

111

**kwargs

112

) -> Connection

113

```

114

115

```python { .api }

116

class Connection:

117

def cursor(self, cursor_style: str = "row", legacy_primitive_types: bool = None) -> Cursor

118

def commit(self) -> None

119

def rollback(self) -> None

120

def close(self) -> None

121

122

class Cursor:

123

def execute(self, operation: str, params: list = None) -> Cursor

124

def executemany(self, operation: str, seq_of_params: list) -> Cursor

125

def fetchone(self) -> Optional[List[Any]]

126

def fetchmany(self, size: int = None) -> List[List[Any]]

127

def fetchall(self) -> List[List[Any]]

128

def describe(self, sql: str) -> List[DescribeOutput]

129

```

130

131

[DB-API Interface](./db-api.md)

132

133

### Low-Level Client

134

135

Direct HTTP protocol implementation providing fine-grained control over query execution, session management, and result handling with support for the spooled protocol.

136

137

```python { .api }

138

class TrinoRequest:

139

def __init__(

140

self,

141

host: str,

142

port: int,

143

client_session: ClientSession,

144

http_session: Optional[Session] = None,

145

**kwargs

146

)

147

def post(self, sql: str, additional_http_headers: Optional[Dict[str, Any]] = None) -> Response

148

def get(self, url: str) -> Response

149

150

class TrinoQuery:

151

def __init__(self, request: TrinoRequest, query: str, **kwargs)

152

def execute(self, additional_http_headers: dict = None) -> TrinoResult

153

def fetch(self) -> List[Union[List[Any]], Any]

154

def cancel(self) -> None

155

```

156

157

[Low-Level Client](./low-level-client.md)

158

159

### Authentication

160

161

Comprehensive authentication support including Basic, JWT, OAuth2, Kerberos, GSSAPI, and client certificate authentication with configurable redirect handlers and token caching.

162

163

```python { .api }

164

class BasicAuthentication:

165

def __init__(self, username: str, password: str)

166

167

class JWTAuthentication:

168

def __init__(self, token: str)

169

170

class OAuth2Authentication:

171

def __init__(self, redirect_auth_url_handler: CompositeRedirectHandler = ...)

172

173

class KerberosAuthentication:

174

def __init__(

175

self,

176

config: Optional[str] = None,

177

service_name: Optional[str] = None,

178

mutual_authentication: int = MUTUAL_REQUIRED,

179

**kwargs

180

)

181

```

182

183

[Authentication](./authentication.md)

184

185

### SQLAlchemy Dialect

186

187

SQLAlchemy dialect implementation enabling ORM usage, connection pooling, and SQL expression language support with Trino-specific type mappings and query compilation.

188

189

```python { .api }

190

from trino.sqlalchemy import URL

191

192

def create_engine(url: str, **kwargs) -> Engine

193

```

194

195

[SQLAlchemy Integration](./sqlalchemy.md)

196

197

### Constants Module

198

199

Default values, HTTP headers, and protocol constants used throughout the client library for configuration and HTTP communication with Trino coordinators.

200

201

```python { .api }

202

# Connection defaults

203

DEFAULT_PORT: int = 8080

204

DEFAULT_TLS_PORT: int = 443

205

DEFAULT_SOURCE: str = "trino-python-client"

206

DEFAULT_CATALOG: Optional[str] = None

207

DEFAULT_SCHEMA: Optional[str] = None

208

DEFAULT_AUTH: Optional[Any] = None

209

DEFAULT_MAX_ATTEMPTS: int = 3

210

DEFAULT_REQUEST_TIMEOUT: float = 30.0

211

212

# Protocol constants

213

HTTP: str = "http"

214

HTTPS: str = "https"

215

URL_STATEMENT_PATH: str = "/v1/statement"

216

CLIENT_NAME: str = "Trino Python Client"

217

218

# HTTP headers

219

HEADER_CATALOG: str = "X-Trino-Catalog"

220

HEADER_SCHEMA: str = "X-Trino-Schema"

221

HEADER_SOURCE: str = "X-Trino-Source"

222

HEADER_USER: str = "X-Trino-User"

223

HEADER_SESSION: str = "X-Trino-Session"

224

HEADER_TRANSACTION: str = "X-Trino-Transaction-Id"

225

HEADER_CLIENT_TAGS: str = "X-Trino-Client-Tags"

226

HEADER_TIMEZONE: str = "X-Trino-Time-Zone"

227

228

# Type classifications

229

LENGTH_TYPES: List[str] = ["char", "varchar"]

230

PRECISION_TYPES: List[str] = ["time", "time with time zone", "timestamp", "timestamp with time zone", "decimal"]

231

SCALE_TYPES: List[str] = ["decimal"]

232

```

233

234

### Logging Module

235

236

Logging utilities for configuring and managing Trino client logging with proper level control and logger hierarchy.

237

238

```python { .api }

239

def get_logger(name: str, log_level: Optional[int] = None) -> logging.Logger

240

"""

241

Create or retrieve logger with optional level configuration.

242

243

Parameters:

244

- name: Logger name (typically __name__)

245

- log_level: Optional logging level override

246

247

Returns:

248

Configured logger instance

249

"""

250

251

# Module constants

252

LEVEL: int = logging.INFO

253

trino_root_logger: logging.Logger # Root logger for trino package

254

```

255

256

## Types

257

258

```python { .api }

259

# Isolation levels for transactions

260

class IsolationLevel(Enum):

261

AUTOCOMMIT = 0

262

READ_UNCOMMITTED = 1

263

READ_COMMITTED = 2

264

REPEATABLE_READ = 3

265

SERIALIZABLE = 4

266

267

# Enhanced temporal types with precision handling

268

class TemporalType(Generic[PythonTemporalType]):

269

def round_to(self, precision: int) -> TemporalType[PythonTemporalType]

270

def to_python_type(self) -> PythonTemporalType

271

272

class Time(TemporalType[time])

273

class TimeWithTimeZone(Time)

274

class Timestamp(TemporalType[datetime])

275

class TimestampWithTimeZone(Timestamp)

276

277

# Named tuple with attribute access for row results

278

class NamedRowTuple(Tuple[Any, ...]):

279

def __init__(self, values: List[Any], names: List[str], types: List[str])

280

```

281

282

## Exception Hierarchy

283

284

```python { .api }

285

# DB-API 2.0 exceptions (PEP 249)

286

class Error(Exception)

287

class Warning(Exception)

288

class InterfaceError(Error)

289

class DatabaseError(Error)

290

class InternalError(DatabaseError)

291

class OperationalError(DatabaseError)

292

class ProgrammingError(DatabaseError)

293

class IntegrityError(DatabaseError)

294

class DataError(DatabaseError)

295

class NotSupportedError(DatabaseError)

296

297

# Trino-specific exceptions

298

class TrinoQueryError(Error):

299

@property

300

def error_code(self) -> Optional[int]

301

@property

302

def error_name(self) -> Optional[str]

303

@property

304

def message(self) -> str

305

@property

306

def query_id(self) -> Optional[str]

307

308

class TrinoExternalError(TrinoQueryError, OperationalError)

309

class TrinoInternalError(TrinoQueryError, InternalError)

310

class TrinoUserError(TrinoQueryError, ProgrammingError)

311

class TrinoAuthError(OperationalError)

312

class TrinoConnectionError(OperationalError)

313

class TrinoDataError(NotSupportedError)

314

315

# HTTP exceptions

316

class HttpError(Exception)

317

class Http502Error(HttpError)

318

class Http503Error(HttpError)

319

class Http504Error(HttpError)

320

```