Pipelines

Ingest with dlt, transform with dbt

Load API data into Iceberg with dlt and transform it with dbt on Trino, from an Airflow task.

dlt and dbt are both preinstalled for pipelines, so a task can import them directly. This page covers what is specific to Databaas: where the credentials come from, how data lands in the catalog, and how dbt reaches Trino. It assumes you know how a pipeline is written.

A complete example

databaas-dlt-dbt-demo is a working pipeline repository that does everything on this page: three dlt sources into Iceberg, a dbt project on Trino, and Cosmos task groups.

Ingest with dlt

A @dlt.source describes an API declaratively (base URL, resources, pagination, authentication), and dlt’s REST API helper handles the requests. See dlt’s REST API source docs for the full configuration.

airflow/example_source_pipeline/source.py
import dlt
from dlt.sources.rest_api import RESTAPIConfig, rest_api_resources


@dlt.source(name="example_source")
def example_source(api_key: str = dlt.secrets.value):
    config: RESTAPIConfig = {
        "client": {
            "base_url": "https://api.example.com/v1/",
            "auth": {
                "type": "api_key",
                "name": "Authorization",
                "api_key": api_key,
                "location": "header",
            },
        },
        "resources": [{"name": "records", "endpoint": {"path": "records"}}],
    }
    yield from rest_api_resources(config)


def fetch_records(api_key: str) -> list[dict]:
    records = list(example_source(api_key=api_key).resources["records"])
    if not records:
        raise RuntimeError("example_source returned no records")
    return records

Pass the API key in as an argument. It comes from an Airflow connection, not from a dlt secrets file: a pipeline task has no .dlt/ directory. See connections and variables.

Write the records into an Iceberg table

When the source returns structured records, write them into Iceberg through get_catalog(). pyarrow infers the schema from the records, nested structures included.

dags/example_source_ingest.py
import pendulum
from airflow.sdk import dag, task
from databaas_utils.airflow import scoped
from databaas_utils.airflow.target import target

NAMESPACE = scoped("example_source")


@dag(
    dag_id=target.dag_id("example_source_ingest"),
    schedule="@daily",
    start_date=pendulum.datetime(2026, 9, 1, tz="UTC"),
    catchup=False,
    is_paused_upon_creation=target.paused,
    tags=target.tags("example_source"),
)
def example_source_ingest():
    @task(retries=3)
    def ingest_records() -> int:
        from datetime import datetime, timezone

        import pyarrow as pa
        from airflow.sdk import BaseHook
        from databaas_utils.airflow import get_catalog
        from example_source_pipeline.source import fetch_records

        api_key = BaseHook.get_connection("source_opendata").password
        fetched_at = datetime.now(timezone.utc).isoformat()
        rows = [{"fetched_at": fetched_at, **r} for r in fetch_records(api_key)]

        catalog = get_catalog()
        catalog.create_namespace_if_not_exists(NAMESPACE)
        data = pa.Table.from_pylist(rows)
        table = catalog.create_table_if_not_exists(f"{NAMESPACE}.records", schema=data.schema)
        table.append(data)
        return data.num_rows

    ingest_records()


example_source_ingest()

This appends: each run adds one more batch of history. If the source hands back a full snapshot instead, overwrite, or overwrite the run’s own slice with a filter as in authoring pipelines. Match the write to what the source gives you.

Land a file instead

When the payload is not tabular yet (a NetCDF or GRIB file, a zip), land it first and parse it in a separate task. Store it with get_store().put(...), record it with get_index().record(...), and return only the URI and key. See files and recording what landed.

Transform with dbt

dbt runs against Trino, reading and writing Iceberg tables through the catalog. The project itself is a standard dbt-trino project: dbt_project.yml, profiles.yml, and a models/ tree with sources.yml and your models. Keep it in your pipeline repository, inside the directory you deploy, next to the DAG.

The catalog is always iceberg

Whatever your pipeline is called, the Trino catalog in profiles.yml (catalog:) and in sources.yml (database:) is the literal iceberg. What dbt-trino calls a schema is a Databaas namespace.

Configure the profile

Trino accepts only a Databaas access token (a JWT), over HTTPS on trino.<your-databaas-domain>. dbt sends it with the jwt method. In a pipeline the token belongs to the service account behind the databaas_lakehouse connection (see set up a service account for pipelines): a task gets a fresh one from databaas_utils.airflow.get_settings(conn_id).auth_header(), and dbt reads and writes only what that service account is granted. Read the token, the output namespace and the catalog from environment variables, so the same profile works in a task and on your laptop:

profiles.yml
example_project:
  target: trino
  outputs:
    trino:
      type: trino
      method: jwt
      jwt_token: "{{ env_var('TRINO_JWT') }}"
      host: "{{ env_var('TRINO_HOST', 'trino.<your-databaas-domain>') }}"
      port: "{{ env_var('DBT_TRINO_PORT', '443') | as_number }}"
      http_scheme: https
      cert: true
      catalog: "{{ env_var('TRINO_CATALOG', 'iceberg') }}"
      schema: "{{ env_var('TRINO_NAMESPACE') }}"
      threads: 4
models/sources.yml
sources:
  - name: example_source
    database: "{{ env_var('TRINO_CATALOG', 'iceberg') }}"
    schema: "{{ env_var('SOURCE_NAMESPACE') }}"
    tables:
      - name: records

See dbt’s Trino profile reference for every other field.

401 Invalid Audience

Trino checks the token’s audience more strictly than the catalog does. If catalog reads and writes work but every dbt run fails with 401 Invalid Audience, the connection’s OAuth scope is missing. See the service account setup.

Run dbt in a task

A branch deploy must write to its own namespaces, like any other pipeline. Compute scoped names, set them and a fresh token in the environment, then invoke dbt:

dags/example_transform.py (excerpt)
from pathlib import Path

from airflow.sdk import task
from databaas_utils.airflow import scoped

DBT_PROJECT_DIR = str(Path(__file__).resolve().parents[1] / "example_dbt")
NAMESPACES = {
    "SOURCE_NAMESPACE": scoped("example_source"),
    "TRINO_NAMESPACE": scoped("example_transformed"),
}


@task
def dbt_run(project_dir: str, namespaces: dict[str, str]) -> None:
    import os

    from databaas_utils.airflow import get_settings
    from dbt.cli.main import dbtRunner

    os.environ["TRINO_CATALOG"] = "iceberg"
    os.environ.update(namespaces)
    # The pipeline's own access token, minted when the task runs.
    os.environ["TRINO_JWT"] = get_settings().auth_header().removeprefix("Bearer ")

    result = dbtRunner().invoke(
        [
            "run",
            "--project-dir", project_dir,
            "--profiles-dir", project_dir,
            "--select", "+my_model",
        ]
    )
    if not result.success:
        failed = [r.message for r in result.result or [] if r.status in ("error", "fail")]
        raise RuntimeError(f"dbt run failed: {result.exception or failed}")

Call it inside your DAG as dbt_run(DBT_PROJECT_DIR, NAMESPACES).

  • Run the whole project as one task with dbt-core’s dbtRunner, and fail the task when dbt fails.
  • Select +my_model, not my_model. The leading + builds every upstream model too; without it, the first run against a fresh branch namespace fails with TABLE_NOT_FOUND.
  • Get the token inside the task, never at the top of the DAG file. It expires within the hour.
  • Raise with the failed nodes’ messages only. dbt’s full result also holds the task’s own arguments, which you do not want in a log.

One Airflow task per model, with Cosmos

The single dbt_run task shows one result for the whole project. To see every model and test as its own task in Airflow, with its own status and log, render the project with Cosmos, which is preinstalled.

Use these settings; the rest of Cosmos works as its documentation describes:

  • Render from a manifest. Set RenderConfig(load_method=LoadMode.DBT_MANIFEST) and point ProjectConfig(manifest_path=...) at target/manifest.json in your dbt project. Airflow reads your DAG files without dbt installed, so Cosmos cannot run dbt ls there.
  • Build the manifest before every deploy. Run dbt parse (any value for TRINO_JWT will do) and deploy the target/manifest.json it writes, as described in the deploy pipeline. Keep target/ out of git.
  • Run in watcher mode. ExecutionConfig(execution_mode=ExecutionMode.WATCHER) runs one dbt build for the whole selection and gives each model and test a sensor that reports its result, so dbt starts once instead of once per model.
  • Fetch the token when the task runs. Cosmos’s built-in Trino JWT mapping reads a fixed token from a connection, and a Databaas token expires within the hour. Subclass it so it asks databaas-utils for a fresh one:
example_dbt_cosmos.py (excerpt)
from cosmos.profiles.trino.jwt import TrinoJWTProfileMapping


class LakehouseTrinoJWTProfileMapping(TrinoJWTProfileMapping):
    airflow_connection_type = "databaas_lakehouse"
    airflow_param_mapping: dict[str, str | list[str]] = {}

    def get_dbt_value(self, name: str):
        if name == "jwt_token":
            from databaas_utils.airflow import get_settings

            return get_settings(self.conn_id).auth_header().removeprefix("Bearer ")
        return super().get_dbt_value(name)

Pass it to ProfileConfig with conn_id="databaas_lakehouse" and the host, port, catalog and scoped output namespace in profile_args, and pass the scoped source namespaces in ProjectConfig(env_vars=...).

Run dbt from your laptop

You can run the same project from your laptop against the real Trino, as yourself instead of as the pipeline. Sign in with databaas login as described in working locally. Then set the environment the profile reads:

  • TRINO_JWT: the access token that databaas token prints. It expires within the hour; run databaas token again for a new one.
  • TRINO_NAMESPACE: a namespace of your own. Always set it. A laptop run writes as you, to whatever namespace you name, including production’s.
  • The source namespaces your sources.yml reads, such as SOURCE_NAMESPACE.

Then run dbt as usual, for example dbt build --project-dir example_dbt --profiles-dir example_dbt, with the dbt-core and dbt-trino versions your pipelines run, from Python packages. Your own login needs grants on the namespaces you read and write.

Trino and Iceberg SQL differences

dbt compiles your SQL; Trino runs it against Iceberg. Each of these shows up as a clear error on the first run and is a one-line fix:

  • Timestamp precision. A bare CAST(... AS timestamp) has precision 3, and Iceberg accepts only 6. Cast to timestamp(6), or the write fails with NOT_SUPPORTED.
  • Parsing timestamp strings. An ISO 8601 string without a timezone or seconds can fail a direct cast with INVALID_CAST_ARGUMENT. Use date_parse(value, '<format>') first, then cast.
  • Unnesting parallel arrays. CROSS JOIN UNNEST(arr1, arr2) AS t(col1, col2) unnests several arrays together, positionally, into one row per element.