Skip to content

Commit f2a2466

Browse files
committed
feat(trino): add support for http headers
1 parent 3a775bc commit f2a2466

9 files changed

Lines changed: 104 additions & 24 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
## [Unreleased]
9+
### Added
10+
- Trino connections support custom HTTP headers via `DATACONTRACT_TRINO_HTTP_HEADERS`
911

1012
## [1.2.8] - 2026-10-26
1113

‎datacontract/config/settings.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import json
56
import logging
67
import os
78
from pathlib import Path
@@ -334,6 +335,7 @@ class Config(BaseSettings):
334335
trino_username: str | None = None
335336
trino_password: SecretStr | None = None
336337
trino_jwt_token: SecretStr | None = None
338+
trino_http_headers: SecretStr | None = None
337339
# overrides for the contract's servers block
338340
trino_host: str | None = None
339341
trino_port: int | None = None
@@ -502,6 +504,29 @@ def _bool_option(self, field_name: str, default: bool) -> bool:
502504
# A set-but-empty variable counts as false, matching pre-Config parsing.
503505
return str(value).strip().lower() in _TRUTHY
504506

507+
def _dict_option(self, field_name: str, required: bool = False) -> dict[str, str] | None:
508+
"""Parse JSON-object or comma-separated ``key=value`` connection properties."""
509+
text = self._str_option(field_name, required)
510+
if not text:
511+
return None
512+
if text.startswith("{"):
513+
try:
514+
parsed = json.loads(text)
515+
except json.JSONDecodeError as e:
516+
key = env_name(field_name, type(self).model_fields[field_name])
517+
server_type = field_name.split("_")[0]
518+
from datacontract.model.exceptions import DataContractException
519+
520+
raise DataContractException(
521+
type=f"{server_type}-connection",
522+
name=f"invalid_mapping_{key}",
523+
reason=f"{key} is not valid JSON: {e}",
524+
engine="datacontract-cli",
525+
)
526+
return {str(k): str(v) for k, v in parsed.items()}
527+
pairs = (pair.partition("=") for pair in text.split(",") if pair.strip())
528+
return {key.strip(): value.strip() for key, _, value in pairs if key.strip()}
529+
505530
# --- entropy ---
506531
def get_entropy_data_api_key(self, required: bool = False) -> str | None:
507532
return self._str_option("entropy_data_api_key", required)
@@ -696,8 +721,8 @@ def get_iceberg_s3_endpoint(self, required: bool = False) -> str | None:
696721
def get_iceberg_signing_name(self, required: bool = False) -> str | None:
697722
return self._str_option("iceberg_signing_name", required)
698723

699-
def get_iceberg_properties(self, required: bool = False) -> str | None:
700-
return self._str_option("iceberg_properties", required)
724+
def get_iceberg_properties(self, required: bool = False) -> dict[str, str] | None:
725+
return self._dict_option("iceberg_properties", required)
701726

702727
def get_iceberg_credential(self, required: bool = False) -> str | None:
703728
return self._str_option("iceberg_credential", required)
@@ -1040,6 +1065,9 @@ def get_trino_password(self, required: bool = False) -> str | None:
10401065
def get_trino_jwt_token(self, required: bool = False) -> str | None:
10411066
return self._str_option("trino_jwt_token", required)
10421067

1068+
def get_trino_http_headers(self, required: bool = False) -> dict[str, str] | None:
1069+
return self._dict_option("trino_http_headers", required)
1070+
10431071
def get_trino_host(self, required: bool = False) -> str | None:
10441072
return self._str_option("trino_host", required)
10451073

‎datacontract/engines/ibis/connections/connect.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -860,6 +860,9 @@ def _connect_trino(ibis, server: Server, config: Config):
860860
database=config.get_trino_catalog() or server.catalog,
861861
schema=config.get_trino_schema() or server.schema_,
862862
)
863+
http_headers = config.get_trino_http_headers()
864+
if http_headers is not None:
865+
kwargs["http_headers"] = http_headers
863866

864867
if authentication == "basic":
865868
user = config.get_trino_username(required=True)

‎datacontract/engines/ibis/connections/iceberg.py‎

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
from __future__ import annotations
1010

11-
import json
1211
import re
1312
from typing import TYPE_CHECKING, Optional
1413

@@ -83,7 +82,7 @@ def catalog_properties(server: Server, config: Config | None = None) -> dict[str
8382
properties["rest.signing-region"] = region
8483
extra = config.get_iceberg_properties()
8584
if extra:
86-
properties.update(_parse_properties(extra))
85+
properties.update(extra)
8786
return properties
8887

8988

@@ -102,24 +101,6 @@ def aws_region(catalog_url: str) -> Optional[str]:
102101
return match.group("region") if match else None
103102

104103

105-
def _parse_properties(text: str) -> dict[str, str]:
106-
"""Extra pyiceberg catalog properties: a JSON object, or ``key=value`` pairs separated by commas."""
107-
text = text.strip()
108-
if text.startswith("{"):
109-
try:
110-
parsed = json.loads(text)
111-
except json.JSONDecodeError as e:
112-
raise DataContractException(
113-
type="iceberg-connection",
114-
name="invalid_properties",
115-
reason=f"DATACONTRACT_ICEBERG_PROPERTIES is not valid JSON: {e}",
116-
engine="datacontract-cli",
117-
)
118-
return {str(k): str(v) for k, v in parsed.items()}
119-
pairs = (pair.partition("=") for pair in text.split(",") if pair.strip())
120-
return {key.strip(): value.strip() for key, _, value in pairs if key.strip()}
121-
122-
123104
def load_iceberg_catalog(server: Server, config: Config | None = None) -> Catalog:
124105
"""Open the server's REST catalog with pyiceberg."""
125106
try:

‎docs/docs/configuration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,7 @@ Every option, by its environment variable name and the matching `Config` field.
412412
| `DATACONTRACT_TRINO_USERNAME` | `trino_username` | string | |
413413
| `DATACONTRACT_TRINO_PASSWORD` | `trino_password` | string (secret) | |
414414
| `DATACONTRACT_TRINO_JWT_TOKEN` | `trino_jwt_token` | string (secret) | |
415+
| `DATACONTRACT_TRINO_HTTP_HEADERS` | `trino_http_headers` | string (secret) | |
415416
| `DATACONTRACT_TRINO_HOST` | `trino_host` | string | Overrides `host` from the contract's `servers` block |
416417
| `DATACONTRACT_TRINO_PORT` | `trino_port` | integer | Overrides `port` from the contract's `servers` block |
417418
| `DATACONTRACT_TRINO_CATALOG` | `trino_catalog` | string | Overrides `catalog` from the contract's `servers` block |

‎docs/docs/reference/trino.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,16 @@ servers:
3232

3333
`host`, `port`, `catalog`, and `schema` come from the contract's `servers` block, and can be overridden with `DATACONTRACT_TRINO_HOST`, `DATACONTRACT_TRINO_PORT`, `DATACONTRACT_TRINO_CATALOG`, and `DATACONTRACT_TRINO_SCHEMA`.
3434

35+
## Custom HTTP headers
36+
37+
Set `DATACONTRACT_TRINO_HTTP_HEADERS` to a JSON object or comma-separated `key=value` pairs:
38+
39+
```bash
40+
export DATACONTRACT_TRINO_HTTP_HEADERS='{"X-Trino-Client-Info":"datacontract-cli","X-Trino-Routing-Group":"analytics"}'
41+
```
42+
43+
Headers are passed to `trino.dbapi.connect(http_headers=...)` for both `datacontract test` and `datacontract import trino`. The JSON or `key=value` string is stored as a secret and masked in `Config` representations.
44+
3545
## Data types
3646

3747
### Importing

‎tests/test_config.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ def test_secrets_do_not_leak_into_repr():
6767
assert config.snowflake_password.get_secret_value() == "super-secret"
6868

6969

70+
def test_trino_http_headers_can_be_configured_by_env_name():
71+
config = Config.resolve({"DATACONTRACT_TRINO_HTTP_HEADERS": '{"X-Trino-Client-Info": "datacontract-cli"}'})
72+
73+
assert config.get_trino_http_headers() == {"X-Trino-Client-Info": "datacontract-cli"}
74+
75+
7076
def test_unknown_options_raise():
7177
with pytest.raises(ValueError, match="snowflake_pasword"):
7278
Config(snowflake_pasword="typo")

‎tests/test_config_file.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,23 @@ def test_from_yaml_maps_sections_to_fields(tmp_path):
5555
assert config.max_errors == 10
5656

5757

58+
def test_from_yaml_parses_trino_http_headers_mapping(tmp_path, monkeypatch):
59+
monkeypatch.setenv("DATACONTRACT_TRINO_HTTP_HEADERS", '{"X-Trino-Routing-Group": "default"}')
60+
monkeypatch.setenv("TRINO_ROUTING_GROUP", "analytics")
61+
value = '{"X-Trino-Client-Info": "datacontract-cli", "X-Trino-Routing-Group": "${TRINO_ROUTING_GROUP}"}'
62+
path = _write_config(
63+
tmp_path,
64+
f"trino:\n http_headers: '{value}'\n",
65+
)
66+
67+
config = Config.from_yaml(path)
68+
69+
assert config.get_trino_http_headers() == {
70+
"X-Trino-Client-Info": "datacontract-cli",
71+
"X-Trino-Routing-Group": "analytics",
72+
}
73+
74+
5875
def test_from_yaml_interpolates_environment_references(tmp_path, monkeypatch):
5976
monkeypatch.setenv("SNOWFLAKE_PASSWORD", "pw-from-env")
6077
path = _write_config(tmp_path, "snowflake:\n password: ${SNOWFLAKE_PASSWORD}\n")

‎tests/test_connect_trino.py‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"DATACONTRACT_TRINO_USERNAME",
1818
"DATACONTRACT_TRINO_PASSWORD",
1919
"DATACONTRACT_TRINO_JWT_TOKEN",
20+
"DATACONTRACT_TRINO_HTTP_HEADERS",
2021
"DATACONTRACT_TRINO_HOST",
2122
"DATACONTRACT_TRINO_PORT",
2223
"DATACONTRACT_TRINO_CATALOG",
@@ -49,8 +50,8 @@ def _server(**kwargs):
4950
return Server(**defaults)
5051

5152

52-
def _connect(server=None):
53-
return connect_ibis(Run.create_run(), data_contract=None, server=server or _server())
53+
def _connect(server=None, config=None):
54+
return connect_ibis(Run.create_run(), data_contract=None, server=server or _server(), config=config)
5455

5556

5657
def test_basic_auth_is_default(env, captured_connect):
@@ -140,3 +141,34 @@ def test_env_variables_override_the_contract_server_details(env, captured_connec
140141
assert captured_connect["port"] == 8443
141142
assert captured_connect["database"] == "env_catalog"
142143
assert captured_connect["schema"] == "env_schema"
144+
145+
146+
def test_http_headers_are_forwarded(env, captured_connect):
147+
env.setenv("DATACONTRACT_TRINO_USERNAME", "my_user")
148+
env.setenv(
149+
"DATACONTRACT_TRINO_HTTP_HEADERS",
150+
'{"X-Trino-Client-Info": "datacontract-cli", "X-Trino-Routing-Group": "analytics"}',
151+
)
152+
153+
_connect()
154+
155+
assert captured_connect["http_headers"] == {
156+
"X-Trino-Client-Info": "datacontract-cli",
157+
"X-Trino-Routing-Group": "analytics",
158+
}
159+
160+
161+
def test_http_headers_key_value_string_is_forwarded(env, captured_connect):
162+
from datacontract import Config
163+
164+
config = Config(
165+
trino_username="my_user",
166+
trino_http_headers="X-Trino-Client-Info=datacontract-cli,X-Trino-Routing-Group=analytics",
167+
)
168+
169+
_connect(config=config)
170+
171+
assert captured_connect["http_headers"] == {
172+
"X-Trino-Client-Info": "datacontract-cli",
173+
"X-Trino-Routing-Group": "analytics",
174+
}

0 commit comments

Comments
 (0)