# Trino Python client
Client for [Trino](https://trino.io/), a distributed SQL engine for interactive and batch big data processing.
Provides a low-level client and a DBAPI 2.0 implementation and a SQLAlchemy adapter.
It supports Python>=3.9 and PyPy.
[![Build Status](https://github.com/trinodb/trino-python-client/workflows/ci/badge.svg)](https://github.com/trinodb/trino-python-client/actions?query=workflow%3Aci+event%3Apush+branch%3Amaster)
[![Trino Slack](https://img.shields.io/static/v1?logo=slack&logoColor=959DA5&label=Slack&labelColor=333a41&message=join%20conversation&color=3AC358)](https://trino.io/slack.html)
[![Trino: The Definitive Guide book download](https://img.shields.io/badge/Trino%3A%20The%20Definitive%20Guide-download-brightgreen)](https://www.starburst.io/info/oreilly-trino-guide/)
## Development
See [DEVELOPMENT](.github/DEVELOPMENT.md) for information about code style,
development process, and guidelines.
See [CONTRIBUTING](.github/CONTRIBUTING.md) for contribution requirements.
## Usage
### The Python Database API (DBAPI)
**Installation**
```
$ pip install trino
```
**Quick Start**
Use the DBAPI interface to query Trino:
if `host` is a valid url, the port and http schema will be automatically determined. For example `https://my-trino-server:9999` will assign the `http_schema` property to `https` and port to `9999`.
```python
from trino.dbapi import connect
conn = connect(
host="<host>",
port=<port>,
user="<username>",
catalog="<catalog>",
schema="<schema>",
)
cur = conn.cursor()
cur.execute("SELECT * FROM system.runtime.nodes")
rows = cur.fetchall()
```
This will query the `system.runtime.nodes` system tables that shows the nodes
in the Trino cluster.
The DBAPI implementation in `trino.dbapi` provides methods to retrieve fewer
rows for example `Cursor.fetchone()` or `Cursor.fetchmany()`. By default
`Cursor.fetchmany()` fetches one row. Please set
`trino.dbapi.Cursor.arraysize` accordingly.
### SQLAlchemy
**Prerequisite**
- Trino server >= 351
**Compatibility**
`trino.sqlalchemy` is compatible with the latest 1.3.x, 1.4.x and 2.0.x SQLAlchemy
versions at the time of release of a particular version of the client.
**Installation**
```
$ pip install trino[sqlalchemy]
```
**Usage**
To connect to Trino using SQLAlchemy, use a connection string (URL) following this pattern:
```
trino://<username>:<password>@<host>:<port>/<catalog>/<schema>
```
NOTE: `password` and `schema` are optional
**Examples**:
```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()
```
In order to pass additional connection attributes use [connect_args](https://docs.sqlalchemy.org/en/14/core/engines.html#sqlalchemy.create_engine.params.connect_args) method.
Attributes can also be passed in the connection string.
```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"]
))
```
## Authentication mechanisms
### Basic authentication
The `BasicAuthentication` class can be used to connect to a Trino cluster configured with
the [Password file, LDAP or Salesforce authentication type](https://trino.io/docs/current/security/authentication-types.html):
- DBAPI
```python
from trino.dbapi import connect
from trino.auth import BasicAuthentication
conn = connect(
user="<username>",
auth=BasicAuthentication("<username>", "<password>"),
http_scheme="https",
...
)
```
- SQLAlchemy
```python
from sqlalchemy import create_engine
engine = create_engine("trino://<username>:<password>@<host>:<port>/<catalog>")
# or as connect_args
from trino.auth import BasicAuthentication
engine = create_engine(
"trino://<username>@<host>:<port>/<catalog>",
connect_args={
"auth": BasicAuthentication("<username>", "<password>"),
"http_scheme": "https",
}
)
```
### JWT authentication
The `JWTAuthentication` class can be used to connect to a Trino cluster configured with
the [`JWT` authentication type](https://trino.io/docs/current/security/jwt.html):
- DBAPI
```python
from trino.dbapi import connect
from trino.auth import JWTAuthentication
conn = connect(
user="<username>",
auth=JWTAuthentication("<jwt_token>"),
http_scheme="https",
...
)
```
- SQLAlchemy
```python
from sqlalchemy import create_engine
engine = create_engine("trino://<username>@<host>:<port>/<catalog>/<schema>?access_token=<jwt_token>")
# or as connect_args
from trino.auth import JWTAuthentication
engine = create_engine(
"trino://<username>@<host>:<port>/<catalog>",
connect_args={
"auth": JWTAuthentication("<jwt_token>"),
"http_scheme": "https",
}
)
```
### OAuth2 authentication
The `OAuth2Authentication` class can be used to connect to a Trino cluster configured with
the [OAuth2 authentication type](https://trino.io/docs/current/security/oauth2.html).
A callback to handle the redirect url can be provided via param `redirect_auth_url_handler` of the `trino.auth.OAuth2Authentication` class. By default, it will try to launch a web browser (`trino.auth.WebBrowserRedirectHandler`) to go through the authentication flow and output the redirect url to stdout (`trino.auth.ConsoleRedirectHandler`). Multiple redirect handlers are combined using the `trino.auth.CompositeRedirectHandler` class.
The OAuth2 token will be cached either per `trino.auth.OAuth2Authentication` instance and username or, when keyring is installed, it will be cached within a secure backend (MacOS keychain, Windows credential locker, etc) under a key including host of the Trino connection. Keyring can be installed using `pip install 'trino[external-authentication-token-cache]'`.
> [!WARNING]
> If username is not specified then the OAuth2 token cache is shared and stored per host.
- DBAPI
```python
from trino.dbapi import connect
from trino.auth import OAuth2Authentication
conn = connect(
user="<username>",
auth=OAuth2Authentication(),
http_scheme="https",
...
)
```
- SQLAlchemy
```python
from sqlalchemy import create_engine
from trino.auth import OAuth2Authentication
engine = create_engine(
"trino://<username>@<host>:<port>/<catalog>",
connect_args={
"auth": OAuth2Authentication(),
"http_scheme": "https",
}
)
```
### Certificate authentication
`CertificateAuthentication` class can be used to connect to Trino cluster configured with [certificate based authentication](https://trino.io/docs/current/security/certificate.html). `CertificateAuthentication` requires paths to a valid client certificate and private key.
- DBAPI
```python
from trino.dbapi import connect
from trino.auth import CertificateAuthentication
conn = connect(
user="<username>",
auth=CertificateAuthentication("/path/to/cert.pem", "/path/to/key.pem"),
http_scheme="https",
...
)
```
- SQLAlchemy
```python
from sqlalchemy import create_engine
from trino.auth import CertificateAuthentication
engine = create_engine("trino://<username>@<host>:<port>/<catalog>/<schema>?cert=<cert>&key=<key>")
# or as connect_args
engine = create_engine(
"trino://<username>@<host>:<port>/<catalog>",
connect_args={
"auth": CertificateAuthentication("/path/to/cert.pem", "/path/to/key.pem"),
"http_scheme": "https",
}
)
```
### Kerberos authentication
Make sure that the Kerberos support is installed using `pip install trino[kerberos]`.
The `KerberosAuthentication` class can be used to connect to a Trino cluster configured with
the [`Kerberos` authentication type](https://trino.io/docs/current/security/kerberos.html):
- DBAPI
```python
from trino.dbapi import connect
from trino.auth import KerberosAuthentication
conn = connect(
user="<username>",
auth=KerberosAuthentication(...),
http_scheme="https",
...
)
```
- SQLAlchemy
```python
from sqlalchemy import create_engine
from trino.auth import KerberosAuthentication
engine = create_engine(
"trino://<username>@<host>:<port>/<catalog>",
connect_args={
"auth": KerberosAuthentication(...),
"http_scheme": "https",
}
)
```
### GSSAPI authentication
Make sure that the GSSAPI support is installed using `pip install trino[gssapi]`.
The `GSSAPIAuthentication` class can be used to connect to a Trino cluster configured with
the [`Kerberos` authentication type](https://trino.io/docs/current/security/kerberos.html):
It follows the interface for `KerberosAuthentication`, but is using
[requests-gssapi](https://github.com/pythongssapi/requests-gssapi), instead of [requests-kerberos](https://github.com/requests/requests-kerberos) under the hood.
- DBAPI
```python
from trino.dbapi import connect
from trino.auth import GSSAPIAuthentication
conn = connect(
user="<username>",
auth=GSSAPIAuthentication(...),
http_scheme="https",
...
)
```
- SQLAlchemy
```python
from sqlalchemy import create_engine
from trino.auth import GSSAPIAuthentication
engine = create_engine(
"trino://<username>@<host>:<port>/<catalog>",
connect_args={
"auth": GSSAPIAuthentication(...),
"http_scheme": "https",
}
)
```
## User impersonation
In the case where user who submits the query is not the same as user who authenticates to Trino server (e.g in Superset),
you can set `username` to be different from `principal_id`. Note that `principal_id` is extracted from `auth`,
for example `username` in BasicAuthentication, `sub` in JWT token or `service-name` in KerberosAuthentication.
You need to make sure that [`principal_id` has permission to impersonate `username`](https://trino.io/docs/current/security/file-system-access-control.html#impersonation-rules).
### Extra credentials
[`Extra credentials`](https://trino.io/docs/current/develop/client-protocol.html#client-request-headers) can be sent as:
```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()
```
## Roles
Authorization roles to use for catalogs, specified as a dict with key-value pairs for the catalog and role. For example, `{"catalog1": "roleA", "catalog2": "roleB"}` sets `roleA` for `catalog1` and `roleB` for `catalog2`. See Trino docs.
```python
import trino
conn = trino.dbapi.connect(
host='localhost',
port=443,
user='the-user',
roles={"catalog1": "roleA", "catalog2": "roleB"},
)
```
You could also pass `system` role without explicitly specifing "system" catalog:
```python
import trino
conn = trino.dbapi.connect(
host='localhost',
port=443,
user='the-user',
roles="role1" # equivalent to {"system": "role1"}
)
```
## Timezone
The time zone for the session can be explicitly set using the IANA time zone
name. When not set the time zone defaults to the client side local timezone.
```python
import trino
conn = trino.dbapi.connect(
host='localhost',
port=443,
user='username',
timezone='Europe/Brussels',
)
```
> **NOTE: The behaviour till version 0.320.0 was the same as setting session timezone to UTC.**
> **To preserve that behaviour pass `timezone='UTC'` when creating the connection.**
## SSL
### SSL verification
In order to disable SSL verification, set the `verify` parameter to `False`.
```python
from trino.dbapi import connect
from trino.auth import BasicAuthentication
conn = connect(
user="<username>",
auth=BasicAuthentication("<username>", "<password>"),
http_scheme="https",
verify=False
)
```
### Self-signed certificates
To use self-signed certificates, specify a path to the certificate in `verify` parameter.
More details can be found in [the Python requests library documentation](https://requests.readthedocs.io/en/latest/user/advanced/#ssl-cert-verification).
```python
from trino.dbapi import connect
from trino.auth import BasicAuthentication
conn = connect(
user="<username>",
auth=BasicAuthentication("<username>", "<password>"),
http_scheme="https",
verify="/path/to/cert.crt"
)
```
## Transactions
The client runs by default in *autocommit* mode. To enable transactions, set
*isolation_level* to a value different than `IsolationLevel.AUTOCOMMIT`:
```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()
```
The transaction is created when the first SQL statement is executed.
`trino.dbapi.Connection.commit()` will be automatically called when the code
exits the *with* context and the queries succeed, otherwise
`trino.dbapi.Connection.rollback()` will be called.
## Legacy Primitive types
By default, the client will convert the results of the query to the
corresponding Python types. For example, if the query returns a `DECIMAL` column, the result will be a `Decimal` object.
If you want to disable this behaviour, set flag `legacy_primitive_types` to `True`.
Limitations of the Python types are described in the
[Python types documentation](https://docs.python.org/3/library/datatypes.html). These limitations will generate an
exception `trino.exceptions.TrinoDataError` if the query returns a value that cannot be converted to the corresponding Python
type.
```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"
```
### Trino to Python type mappings
| Trino type | Python type |
|------------|-------------------|
| BOOLEAN | bool |
| TINYINT | int |
| SMALLINT | int |
| INTEGER | int |
| BIGINT | int |
| REAL | float |
| DOUBLE | float |
| DECIMAL | decimal.Decimal |
| VARCHAR | str |
| CHAR | str |
| VARBINARY | bytes |
| DATE | datetime.date |
| TIME | datetime.time |
| TIMESTAMP | datetime.datetime |
| ARRAY | list |
| MAP | dict |
| ROW | tuple |
Trino types other than those listed above are not mapped to Python types. To use those use [legacy primitive types](#legacy-primitive-types).
# Need help?
Feel free to create an issue as it makes your request visible to other users and contributors.
If an interactive discussion would be better or if you just want to hangout and chat about
the Trino Python client, you can join us on the *#python-client* channel on
[Trino Slack](https://trino.io/slack.html).
Raw data
{
"_id": null,
"home_page": "https://github.com/trinodb/trino-python-client",
"name": "trino",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": null,
"author": "Trino Team",
"author_email": "python-client@trino.io",
"download_url": "https://files.pythonhosted.org/packages/99/80/56716b9ee69e769cd2babc2dfe58d601ea7f244a2e67a7ef02f7fd3bd3df/trino-0.331.0.tar.gz",
"platform": null,
"description": "# Trino Python client\n\nClient for [Trino](https://trino.io/), a distributed SQL engine for interactive and batch big data processing.\nProvides a low-level client and a DBAPI 2.0 implementation and a SQLAlchemy adapter.\nIt supports Python>=3.9 and PyPy.\n\n[![Build Status](https://github.com/trinodb/trino-python-client/workflows/ci/badge.svg)](https://github.com/trinodb/trino-python-client/actions?query=workflow%3Aci+event%3Apush+branch%3Amaster)\n[![Trino Slack](https://img.shields.io/static/v1?logo=slack&logoColor=959DA5&label=Slack&labelColor=333a41&message=join%20conversation&color=3AC358)](https://trino.io/slack.html)\n[![Trino: The Definitive Guide book download](https://img.shields.io/badge/Trino%3A%20The%20Definitive%20Guide-download-brightgreen)](https://www.starburst.io/info/oreilly-trino-guide/)\n\n## Development\n\nSee [DEVELOPMENT](.github/DEVELOPMENT.md) for information about code style,\ndevelopment process, and guidelines.\n\nSee [CONTRIBUTING](.github/CONTRIBUTING.md) for contribution requirements.\n\n## Usage\n\n### The Python Database API (DBAPI)\n\n**Installation**\n\n```\n$ pip install trino\n```\n\n**Quick Start**\n\nUse the DBAPI interface to query Trino:\n\nif `host` is a valid url, the port and http schema will be automatically determined. For example `https://my-trino-server:9999` will assign the `http_schema` property to `https` and port to `9999`.\n\n```python\nfrom trino.dbapi import connect\n\nconn = connect(\n host=\"<host>\",\n port=<port>,\n user=\"<username>\",\n catalog=\"<catalog>\",\n schema=\"<schema>\",\n)\ncur = conn.cursor()\ncur.execute(\"SELECT * FROM system.runtime.nodes\")\nrows = cur.fetchall()\n```\n\nThis will query the `system.runtime.nodes` system tables that shows the nodes\nin the Trino cluster.\n\nThe DBAPI implementation in `trino.dbapi` provides methods to retrieve fewer\nrows for example `Cursor.fetchone()` or `Cursor.fetchmany()`. By default\n`Cursor.fetchmany()` fetches one row. Please set\n`trino.dbapi.Cursor.arraysize` accordingly.\n\n### SQLAlchemy\n\n**Prerequisite**\n\n- Trino server >= 351\n\n**Compatibility**\n\n`trino.sqlalchemy` is compatible with the latest 1.3.x, 1.4.x and 2.0.x SQLAlchemy\nversions at the time of release of a particular version of the client.\n\n**Installation**\n\n```\n$ pip install trino[sqlalchemy]\n```\n\n**Usage**\n\nTo connect to Trino using SQLAlchemy, use a connection string (URL) following this pattern:\n\n```\ntrino://<username>:<password>@<host>:<port>/<catalog>/<schema>\n```\n\nNOTE: `password` and `schema` are optional\n\n**Examples**:\n\n```python\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.schema import Table, MetaData\nfrom sqlalchemy.sql.expression import select, text\n\nengine = create_engine('trino://user@localhost:8080/system')\nconnection = engine.connect()\n\nrows = connection.execute(text(\"SELECT * FROM runtime.nodes\")).fetchall()\n\n# or using SQLAlchemy schema\nnodes = Table(\n 'nodes',\n MetaData(schema='runtime'),\n autoload=True,\n autoload_with=engine\n)\nrows = connection.execute(select(nodes)).fetchall()\n```\n\nIn order to pass additional connection attributes use [connect_args](https://docs.sqlalchemy.org/en/14/core/engines.html#sqlalchemy.create_engine.params.connect_args) method.\nAttributes can also be passed in the connection string.\n\n```python\nfrom sqlalchemy import create_engine\nfrom trino.sqlalchemy import URL\n\nengine = create_engine(\n URL(\n host=\"localhost\",\n port=8080,\n catalog=\"system\"\n ),\n connect_args={\n \"session_properties\": {'query_max_run_time': '1d'},\n \"client_tags\": [\"tag1\", \"tag2\"],\n \"roles\": {\"catalog1\": \"role1\"},\n }\n)\n\n# or in connection string\nengine = create_engine(\n 'trino://user@localhost:8080/system?'\n 'session_properties={\"query_max_run_time\": \"1d\"}'\n '&client_tags=[\"tag1\", \"tag2\"]'\n '&roles={\"catalog1\": \"role1\"}'\n)\n\n# or using the URL factory method\nengine = create_engine(URL(\n host=\"localhost\",\n port=8080,\n client_tags=[\"tag1\", \"tag2\"]\n))\n```\n\n## Authentication mechanisms\n\n### Basic authentication\n\nThe `BasicAuthentication` class can be used to connect to a Trino cluster configured with\nthe [Password file, LDAP or Salesforce authentication type](https://trino.io/docs/current/security/authentication-types.html):\n\n- DBAPI\n\n ```python\n from trino.dbapi import connect\n from trino.auth import BasicAuthentication\n\n conn = connect(\n user=\"<username>\",\n auth=BasicAuthentication(\"<username>\", \"<password>\"),\n http_scheme=\"https\",\n ...\n )\n ```\n\n- SQLAlchemy\n\n ```python\n from sqlalchemy import create_engine\n\n engine = create_engine(\"trino://<username>:<password>@<host>:<port>/<catalog>\")\n\n # or as connect_args\n from trino.auth import BasicAuthentication\n engine = create_engine(\n \"trino://<username>@<host>:<port>/<catalog>\",\n connect_args={\n \"auth\": BasicAuthentication(\"<username>\", \"<password>\"),\n \"http_scheme\": \"https\",\n }\n )\n ```\n\n### JWT authentication\n\nThe `JWTAuthentication` class can be used to connect to a Trino cluster configured with\nthe [`JWT` authentication type](https://trino.io/docs/current/security/jwt.html):\n\n- DBAPI\n\n ```python\n from trino.dbapi import connect\n from trino.auth import JWTAuthentication\n\n conn = connect(\n user=\"<username>\",\n auth=JWTAuthentication(\"<jwt_token>\"),\n http_scheme=\"https\",\n ...\n )\n ```\n\n- SQLAlchemy\n\n ```python\n from sqlalchemy import create_engine\n\n engine = create_engine(\"trino://<username>@<host>:<port>/<catalog>/<schema>?access_token=<jwt_token>\")\n\n # or as connect_args\n from trino.auth import JWTAuthentication\n engine = create_engine(\n \"trino://<username>@<host>:<port>/<catalog>\",\n connect_args={\n \"auth\": JWTAuthentication(\"<jwt_token>\"),\n \"http_scheme\": \"https\",\n }\n )\n ```\n\n### OAuth2 authentication\n\nThe `OAuth2Authentication` class can be used to connect to a Trino cluster configured with\nthe [OAuth2 authentication type](https://trino.io/docs/current/security/oauth2.html).\n\nA callback to handle the redirect url can be provided via param `redirect_auth_url_handler` of the `trino.auth.OAuth2Authentication` class. By default, it will try to launch a web browser (`trino.auth.WebBrowserRedirectHandler`) to go through the authentication flow and output the redirect url to stdout (`trino.auth.ConsoleRedirectHandler`). Multiple redirect handlers are combined using the `trino.auth.CompositeRedirectHandler` class.\n\nThe OAuth2 token will be cached either per `trino.auth.OAuth2Authentication` instance and username or, when keyring is installed, it will be cached within a secure backend (MacOS keychain, Windows credential locker, etc) under a key including host of the Trino connection. Keyring can be installed using `pip install 'trino[external-authentication-token-cache]'`.\n\n> [!WARNING]\n> If username is not specified then the OAuth2 token cache is shared and stored per host.\n\n- DBAPI\n\n ```python\n from trino.dbapi import connect\n from trino.auth import OAuth2Authentication\n\n conn = connect(\n user=\"<username>\",\n auth=OAuth2Authentication(),\n http_scheme=\"https\",\n ...\n )\n ```\n\n- SQLAlchemy\n\n ```python\n from sqlalchemy import create_engine\n from trino.auth import OAuth2Authentication\n\n engine = create_engine(\n \"trino://<username>@<host>:<port>/<catalog>\",\n connect_args={\n \"auth\": OAuth2Authentication(),\n \"http_scheme\": \"https\",\n }\n )\n ```\n\n### Certificate authentication\n\n`CertificateAuthentication` class can be used to connect to Trino cluster configured with [certificate based authentication](https://trino.io/docs/current/security/certificate.html). `CertificateAuthentication` requires paths to a valid client certificate and private key.\n\n- DBAPI\n\n ```python\n from trino.dbapi import connect\n from trino.auth import CertificateAuthentication\n\n conn = connect(\n user=\"<username>\",\n auth=CertificateAuthentication(\"/path/to/cert.pem\", \"/path/to/key.pem\"),\n http_scheme=\"https\",\n ...\n )\n ```\n\n- SQLAlchemy\n\n ```python\n from sqlalchemy import create_engine\n from trino.auth import CertificateAuthentication\n\n engine = create_engine(\"trino://<username>@<host>:<port>/<catalog>/<schema>?cert=<cert>&key=<key>\")\n\n # or as connect_args\n engine = create_engine(\n \"trino://<username>@<host>:<port>/<catalog>\",\n connect_args={\n \"auth\": CertificateAuthentication(\"/path/to/cert.pem\", \"/path/to/key.pem\"),\n \"http_scheme\": \"https\",\n }\n )\n ```\n\n### Kerberos authentication\n\nMake sure that the Kerberos support is installed using `pip install trino[kerberos]`.\nThe `KerberosAuthentication` class can be used to connect to a Trino cluster configured with\nthe [`Kerberos` authentication type](https://trino.io/docs/current/security/kerberos.html):\n\n- DBAPI\n\n ```python\n from trino.dbapi import connect\n from trino.auth import KerberosAuthentication\n\n conn = connect(\n user=\"<username>\",\n auth=KerberosAuthentication(...),\n http_scheme=\"https\",\n ...\n )\n ```\n\n- SQLAlchemy\n\n ```python\n from sqlalchemy import create_engine\n from trino.auth import KerberosAuthentication\n\n engine = create_engine(\n \"trino://<username>@<host>:<port>/<catalog>\",\n connect_args={\n \"auth\": KerberosAuthentication(...),\n \"http_scheme\": \"https\",\n }\n )\n ```\n\n### GSSAPI authentication\n\nMake sure that the GSSAPI support is installed using `pip install trino[gssapi]`.\nThe `GSSAPIAuthentication` class can be used to connect to a Trino cluster configured with\nthe [`Kerberos` authentication type](https://trino.io/docs/current/security/kerberos.html):\n\nIt follows the interface for `KerberosAuthentication`, but is using\n[requests-gssapi](https://github.com/pythongssapi/requests-gssapi), instead of [requests-kerberos](https://github.com/requests/requests-kerberos) under the hood.\n\n- DBAPI\n\n ```python\n from trino.dbapi import connect\n from trino.auth import GSSAPIAuthentication\n\n conn = connect(\n user=\"<username>\",\n auth=GSSAPIAuthentication(...),\n http_scheme=\"https\",\n ...\n )\n ```\n\n- SQLAlchemy\n\n ```python\n from sqlalchemy import create_engine\n from trino.auth import GSSAPIAuthentication\n\n engine = create_engine(\n \"trino://<username>@<host>:<port>/<catalog>\",\n connect_args={\n \"auth\": GSSAPIAuthentication(...),\n \"http_scheme\": \"https\",\n }\n )\n ```\n\n## User impersonation\n\nIn the case where user who submits the query is not the same as user who authenticates to Trino server (e.g in Superset),\nyou can set `username` to be different from `principal_id`. Note that `principal_id` is extracted from `auth`,\nfor example `username` in BasicAuthentication, `sub` in JWT token or `service-name` in KerberosAuthentication.\nYou need to make sure that [`principal_id` has permission to impersonate `username`](https://trino.io/docs/current/security/file-system-access-control.html#impersonation-rules).\n\n### Extra credentials\n\n[`Extra credentials`](https://trino.io/docs/current/develop/client-protocol.html#client-request-headers) can be sent as:\n\n```python\nimport trino\nconn = trino.dbapi.connect(\n host='localhost',\n port=443,\n user='the-user',\n extra_credential=[('a.username', 'bar'), ('a.password', 'foo')],\n)\n\ncur = conn.cursor()\ncur.execute('SELECT * FROM system.runtime.nodes')\nrows = cur.fetchall()\n```\n\n## Roles\n\nAuthorization roles to use for catalogs, specified as a dict with key-value pairs for the catalog and role. For example, `{\"catalog1\": \"roleA\", \"catalog2\": \"roleB\"}` sets `roleA` for `catalog1` and `roleB` for `catalog2`. See Trino docs.\n\n```python\nimport trino\nconn = trino.dbapi.connect(\n host='localhost',\n port=443,\n user='the-user',\n roles={\"catalog1\": \"roleA\", \"catalog2\": \"roleB\"},\n)\n```\n\nYou could also pass `system` role without explicitly specifing \"system\" catalog:\n\n```python\nimport trino\nconn = trino.dbapi.connect(\n host='localhost',\n port=443,\n user='the-user',\n roles=\"role1\" # equivalent to {\"system\": \"role1\"}\n)\n```\n\n## Timezone\n\nThe time zone for the session can be explicitly set using the IANA time zone\nname. When not set the time zone defaults to the client side local timezone.\n\n```python\nimport trino\nconn = trino.dbapi.connect(\n host='localhost',\n port=443,\n user='username',\n timezone='Europe/Brussels',\n)\n```\n\n> **NOTE: The behaviour till version 0.320.0 was the same as setting session timezone to UTC.**\n> **To preserve that behaviour pass `timezone='UTC'` when creating the connection.**\n\n## SSL\n\n### SSL verification\n\nIn order to disable SSL verification, set the `verify` parameter to `False`.\n\n```python\nfrom trino.dbapi import connect\nfrom trino.auth import BasicAuthentication\n\nconn = connect(\n user=\"<username>\",\n auth=BasicAuthentication(\"<username>\", \"<password>\"),\n http_scheme=\"https\",\n verify=False\n)\n```\n\n### Self-signed certificates\n\nTo use self-signed certificates, specify a path to the certificate in `verify` parameter.\nMore details can be found in [the Python requests library documentation](https://requests.readthedocs.io/en/latest/user/advanced/#ssl-cert-verification).\n\n```python\nfrom trino.dbapi import connect\nfrom trino.auth import BasicAuthentication\n\nconn = connect(\n user=\"<username>\",\n auth=BasicAuthentication(\"<username>\", \"<password>\"),\n http_scheme=\"https\",\n verify=\"/path/to/cert.crt\"\n)\n```\n\n## Transactions\n\nThe client runs by default in *autocommit* mode. To enable transactions, set\n*isolation_level* to a value different than `IsolationLevel.AUTOCOMMIT`:\n\n```python\nfrom trino.dbapi import connect\nfrom trino.transaction import IsolationLevel\n\nwith connect(\n isolation_level=IsolationLevel.REPEATABLE_READ,\n ...\n) as conn:\n cur = conn.cursor()\n cur.execute('INSERT INTO sometable VALUES (1, 2, 3)')\n cur.fetchall()\n cur.execute('INSERT INTO sometable VALUES (4, 5, 6)')\n cur.fetchall()\n```\n\nThe transaction is created when the first SQL statement is executed.\n`trino.dbapi.Connection.commit()` will be automatically called when the code\nexits the *with* context and the queries succeed, otherwise\n`trino.dbapi.Connection.rollback()` will be called.\n\n## Legacy Primitive types\n\nBy default, the client will convert the results of the query to the\ncorresponding Python types. For example, if the query returns a `DECIMAL` column, the result will be a `Decimal` object.\nIf you want to disable this behaviour, set flag `legacy_primitive_types` to `True`.\n\nLimitations of the Python types are described in the \n[Python types documentation](https://docs.python.org/3/library/datatypes.html). These limitations will generate an \nexception `trino.exceptions.TrinoDataError` if the query returns a value that cannot be converted to the corresponding Python \ntype.\n\n```python\nimport trino\n\nconn = trino.dbapi.connect(\n legacy_primitive_types=True,\n ...\n)\n\ncur = conn.cursor()\n# Negative DATE cannot be represented with Python types\n# legacy_primitive_types needs to be enabled\ncur.execute(\"SELECT DATE '-2001-08-22'\")\nrows = cur.fetchall()\n\nassert rows[0][0] == \"-2001-08-22\"\nassert cur.description[0][1] == \"date\"\n```\n\n### Trino to Python type mappings\n\n| Trino type | Python type |\n|------------|-------------------|\n| BOOLEAN | bool |\n| TINYINT | int |\n| SMALLINT | int |\n| INTEGER | int |\n| BIGINT | int |\n| REAL | float |\n| DOUBLE | float |\n| DECIMAL | decimal.Decimal |\n| VARCHAR | str |\n| CHAR | str |\n| VARBINARY | bytes |\n| DATE | datetime.date |\n| TIME | datetime.time |\n| TIMESTAMP | datetime.datetime |\n| ARRAY | list |\n| MAP | dict |\n| ROW | tuple |\n\nTrino types other than those listed above are not mapped to Python types. To use those use [legacy primitive types](#legacy-primitive-types).\n\n# Need help?\n\nFeel free to create an issue as it makes your request visible to other users and contributors.\n\nIf an interactive discussion would be better or if you just want to hangout and chat about\nthe Trino Python client, you can join us on the *#python-client* channel on\n[Trino Slack](https://trino.io/slack.html).\n",
"bugtrack_url": null,
"license": "Apache 2.0",
"summary": "Client for the Trino distributed SQL Engine",
"version": "0.331.0",
"project_urls": {
"Homepage": "https://github.com/trinodb/trino-python-client"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "2daacce7a726e314fbeae9fed8ed5d6bd4af19796286d7ee82f120e3633da74c",
"md5": "0382beee4107bd26bb5e203a7096a119",
"sha256": "4f909e6c2966d23917e2538bc7f342d5dcc6e512102811fb1e53bdaf15bd49e3"
},
"downloads": -1,
"filename": "trino-0.331.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "0382beee4107bd26bb5e203a7096a119",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 53771,
"upload_time": "2024-12-10T07:24:20",
"upload_time_iso_8601": "2024-12-10T07:24:20.351007Z",
"url": "https://files.pythonhosted.org/packages/2d/aa/cce7a726e314fbeae9fed8ed5d6bd4af19796286d7ee82f120e3633da74c/trino-0.331.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "998056716b9ee69e769cd2babc2dfe58d601ea7f244a2e67a7ef02f7fd3bd3df",
"md5": "0c516ace4965c20d4017e396baef5e6f",
"sha256": "2d9acdf7b19d136c97c98e55599fb9a5556e124282b0a40afb93bdfbb5371708"
},
"downloads": -1,
"filename": "trino-0.331.0.tar.gz",
"has_sig": false,
"md5_digest": "0c516ace4965c20d4017e396baef5e6f",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 50851,
"upload_time": "2024-12-10T07:24:22",
"upload_time_iso_8601": "2024-12-10T07:24:22.784398Z",
"url": "https://files.pythonhosted.org/packages/99/80/56716b9ee69e769cd2babc2dfe58d601ea7f244a2e67a7ef02f7fd3bd3df/trino-0.331.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-10 07:24:22",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "trinodb",
"github_project": "trino-python-client",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "trino"
}