Skip to content

Data Build Tool Summary

Version
  • Update 11/2026: add more how tos. Fix grammar and typos
  • Updated 08/2026: Cleaned structure
  • Created 03/2026

Context

  • Before dbt, analytics and data teams wrote SQL transformations directly against the warehouse by hand with virtually no version control, tests, reusable dependencies, or documentation. dbt was created to treat SQL transformations as software and is now the standard for modern data transformation workflows.
  • Dependencies are managed by dbt, while tests and documentation are fully version-controlled.
  • dbt Core is an open-source, database-agnostic ELT CLI tool that enables data analysts and engineers to build reliable, modular data pipelines. It structures transformations into "models" (SELECT statements) that are version-controlled, automatically documented, and tested for quality before consumption by downstream analytics tools. Learn more about dbt in the official documentation.
  • dbt Cloud is the managed SaaS platform providing a web-based IDE, scheduler, job orchestration, alerting, and monitoring.

It is supported by major ISVs across the lakehouse and data warehouse industry.

Confluent has developed a dbt adapter (dbt-confluent) to deploy and manage Flink SQL statements on Confluent Cloud for Flink. It supports standard dbt commands (init, debug, run, test, docs generate, etc.) against Confluent Cloud for Flink, allowing data teams to manage streaming pipelines end-to-end with dbt rather than relying solely on Terraform or the Confluent CLI.

This guide first covers a concrete data warehouse example with DuckDB, followed by a Confluent Cloud Flink project.

See the Confluent Cloud product documentation on dbt.

Use Cases

Typical dbt use cases include:

  • Modeling changes that are easy to review, track, and revert in Git
  • Explicit dependency graphs between models (DAGs)
  • Automated data quality and contract tests
  • Incremental loading of fact tables
  • Tracking historical changes in dimension tables (SCD Type 2)
  • Automated testing, documentation generation, and interactive data lineage visualization

dbt cli install

  • Python is required, and dbt should be installed in a virtual environment (see installation instructions and Python version compatibility).
  • Create a ~/.dbt directory where dbt stores the profiles.yml file containing user and connection credentials.
  • Initialize a virtual environment under your project folder (e.g. dbt):
    uv venv
    source .venv/bin/activate
    
  • Install the dbt adapter for DuckDB:

    uv add dbt-duckdb
    

  • Install the dbt adapter for Confluent Cloud for Flink:

    uv add dbt-confluent
    

  • Upgrade:

    uv pip install --upgrade dbt-confluent
    

Getting started

We will start by scaffolding a project, then explore core concepts while implementing working examples.

A dbt project is a directory containing SQL model files (.sql) and YAML configuration files. It can be version-controlled in Git and automated as part of CI/CD workflows.

A data warehouse example

This example is located in code/dbt/airbnb and uses DuckDB as its database engine.

  1. Create the dbt project:

    dbt init airbnb
    

    Running this command prompts you to select a dbt profile (e.g. duckdb). A profile is stored in ~/.dbt/profiles.yml and holds connection credentials for target data platforms. Running dbt init appends a configuration block such as:

    airbnb:
      outputs:
        dev:
          type: duckdb
          path: dev.duckdb
          threads: 1
    
        prod:
          type: duckdb
          path: prod.duckdb
          threads: 4
    
      target: dev
    

    This defines two target outputs (dev and prod) with their respective connection parameters. The path specifies where the local DuckDB database file will be created.

    dbt also generates standard project directories:

    models
    analyses
    tests
    seeds
    macros
    snapshots
    

    and a dbt_project.yml file defining overall project settings.

  2. Understanding dbt_project.yml:

    • It references the profile name to use:
      profile: 'airbnb'
      
    • Default configurations (such as materialization strategies) can be defined at the project or directory level:
      models:
        airbnb:
          +materialized: view
      

Next, we explore core dbt concepts with concrete examples.

Flink SQL queries are defined as dbt models. dbt compiles and deploys them to Confluent Cloud via the Flink Statements REST API. When adopting a "shift-left" strategy that moves dimensional data modeling (star schema) into real-time streaming, data teams can manage streaming pipelines with the same software engineering workflows used for data warehouses.

  • Create the project:
    dbt init flink_workshop
    

The dbt profile in ~/.dbt/profiles.yml can reference environment variables for API keys and secrets:

flink_workshop:
  outputs:
    dev:
      cloud_provider: aws
      cloud_region: us-west-2
      compute_pool_id: lfcp-
      dbname: j9r-kafka
      environment_id: env-
      execution_mode: streaming_query
      flink_api_key: "{{ env_var('CONFLUENT_FLINK_API_KEY') }}"
      flink_api_secret: "{{ env_var('CONFLUENT_FLINK_API_SECRET') }}"
      organization_id: 49......44
      statement_label: dbt-confluent
      statement_name_prefix: dbt-
      threads: 1
      type: confluent

This connection can be referenced across dbt projects via dbt_project.yml:

name: 'flink_workshop'
version: '1.0.0'
profile: 'cc_flink'

You can rename the profile stanza to cc_flink to represent the Confluent Cloud connection.

Major dbt Concepts

  • Transformations in dbt with a data warehouse (like DuckDB or Snowflake) are managed through different materialization strategies:

    • Table: Replaces the entire target table with each run. Ideal for smaller datasets or full-refresh batches.
    • Incremental: Updates only new or changed data using append, merge, or delete+insert.
    • Microbatch: Breaks massive datasets into smaller, time-based segments (e.g., daily) that process independently.
    • External: Reads from and exports results directly to files (Parquet, CSV, JSON) on local storage or S3 buckets.
  • dbt encourages building complex transformations in smaller, reusable SQL steps, reducing repetitive code.

  • dbt uses Jinja templating, built-in functions, and macros to dynamically generate SQL and manage dependencies.
  • The required dbt_project.yml file configures project-wide settings. dbt distinguishes folder hierarchies from configuration properties using the + prefix (e.g., +materialized: view).
  • Models: The core building blocks of business logic, defined as SQL SELECT statements that compile into tables or views. Models can reference each other using {{ ref() }} and leverage Jinja macros.
  • Resource Types: Include models, seeds, snapshots, tests, and sources.
  • Properties: Describe resources, column metadata, and data contracts in YAML files.
  • Configurations: Control how dbt builds resources in the target engine. Configurations can be set globally in dbt_project.yml, at the folder level in YAML files, or inline inside SQL models using the config() macro.

Models

Models are organized in logical layers to keep data pipelines clean and scalable, forming a Directed Acyclic Graph (DAG):

  • Staging (stg_ / src_): Clean and rename raw data (e.g., lowercase names, cast types).
  • Intermediate (int_): Perform complex joins, aggregations, and business logic.
  • Marts (fct_ or dim_): Final, analytics-ready models.

The table below summarizes when to use Views versus Tables:

Dimension View Table
Purpose Minor transformations or lightweight abstractions Heavy transformations and aggregations
Execution Computed dynamically at query time Pre-executed, with results stored in tables
Storage None (metadata only) Requires physical storage
Performance Multiple chained views can slow query performance Precomputed data provides fast read performance
  • dbt provides built-in data tests (e.g., uniqueness, non-null checks) to validate assumptions and catch regressions.
  • Schema/Contract: Defines column metadata, data types, and constraints in companion YAML files.
  • Two macros manage table references: {{ ref() }} references other dbt models in the project, while {{ source() }} references declared raw/external tables.
Create the first model

See the DuckDB example for detailed steps on building an analytical data warehouse. In this pattern, an ETL process loads raw data into the warehouse's raw schema:

Once raw tables are present, declare dbt sources and build dimensional models (dimensions and facts) for analytical data products.

In a Flink streaming project, raw events land in Kafka topics, and Flink SQL queries perform real-time transformations from bronze (raw) to silver and gold data products.

Create silver layer

Sources are defined using a YAML file sources.yml inside your models/ directory:

sources:
  - name: airbnb  # Internal dbt name for the source
    schema: raw   # Target schema name in your warehouse
    tables:
      - name: listings # Logical name referenced in dbt models
        identifier: raw_listings # Actual physical table name in the warehouse

Tables defined in sources.yml are referenced in SQL models using {{ source('airbnb', 'listings') }}.

From there, the first development step is to clean raw tables into staging/source models (src_ or stg_), filtering records, deduplicating keys, and normalizing columns. These models can be stored under models/src/:

The following SQL performs classical deduplication:

WITH ranked_hosts AS (
    SELECT
        *,
        ROW_NUMBER() OVER (
            PARTITION BY id
            ORDER BY updated_at DESC, created_at DESC
        ) AS row_num
    FROM
        {{ source('airbnb', 'hosts') }}
    WHERE id IS NOT NULL
)
SELECT
    id AS host_id,
    name AS host_name,
    is_superhost,
    created_at,
    updated_at
FROM
    ranked_hosts
WHERE
    row_num = 1

Running the following command creates the new table with cleaned records:

dbt run --target dev
# returns
Found 1 seed, 3 sources, 474 macros

You can validate this by querying the DuckDB database:

duckdb data/airbnb.duckdb
-- in the shell
select * from main.src_hosts;

The same process applies to raw_reviews and raw_listings.

To monitor source freshness, define freshness thresholds on raw tables using a timestamp or date column in sources.yml.

Project structure

dbt recursively scans all directories specified in model-paths (default models/). Commands like dbt run, dbt build, and dbt compile automatically discover and execute those .sql files.

The folder structure under models/ can follow Kimball dimensional modeling or domain-driven data products (see project management methodology):

models/
  sources/
    hosts/
      src_hosts.sql
    listings/
      src_listings.sql
  dimensions/
    hosts/
      dim_hosts_cleansed.sql
  facts/
    reviews/
      fct_reviews.sql

dbt names a model from its filename, not from its folder path:

  • For models/src/src_hosts.sql, the model name is src_hosts.
  • Reference it with ref('src_hosts'), not ref('src.hosts.src_hosts').

Because dbt identifies models by filename, identical filenames in different subfolders cause name collisions. Always use unique filenames (e.g., dim_hosts.sql, fct_reviews.sql) or configure explicit model aliases.

  • To run specific models or subdirectories, use node selection syntax:
    uv run dbt run --select dimensions.hosts
    # or select all dimensions:
    uv run dbt run --select dimensions.*
    
    # Select a single model with full refresh
    uv run dbt run --select withdrawals_by_account --target dev --full-refresh
    

Materializations

dbt supports four primary materialization types for models:

  • View: Lightweight SQL view rebuilt at runtime when queried; stores no physical data.
  • Table: Physical table created and fully overwritten on each dbt run.
  • Incremental: Appends or merges only new/modified records since the previous run, avoiding full table rewrites.
  • Ephemeral: Injected as a Common Table Expression (CTE) into downstream models; does not create a database object.

Materializations can be configured in dbt_project.yml by folder:

models:
  airbnb:
    +materialized: view
    dimensions:
      +materialized: table
    src:
      +materialized: ephemeral

Materialization can also be defined per model using the config() block:

  • Add config() to a dimensional SQL model:
    {{
      config(
        materialized = 'view'
      )
    }}
    SELECT
      listing_id,
      listing_name,
      room_type,
      CASE
        WHEN minimum_nights = 0 THEN 1
        ELSE minimum_nights
      END AS minimum_nights,
      host_id,
      CAST(
        REPLACE(price_str, '$', '') AS DECIMAL(10, 2)
      ) AS price,
      created_at,
      updated_at
    FROM {{ ref('src_listings') }}
    

Incremental

By default, table models are dropped and recreated on each run. For large fact tables, incremental materialization processes only new or changed records. The on_schema_change='fail' setting guards against unexpected schema drift:

{{
  config(
    materialized = 'incremental',
    on_schema_change = 'fail'
  )
}}
WITH src_reviews AS (
  SELECT * FROM {{ ref('src_reviews') }}
)
SELECT * FROM src_reviews
WHERE review_text IS NOT NULL

{% if is_incremental() %}
  AND review_date > (SELECT MAX(review_date) FROM {{ this }})
{% endif %}

The is_incremental() Jinja macro ensures that on subsequent runs, only records with a timestamp greater than the current maximum in the target table ({{ this }}) are processed.

  • Executing dbt run with fct_reviews in incremental mode processes only new records added to raw_reviews:

    INSERT INTO raw_reviews VALUES(3176, CURRENT_TIMESTAMP(), 'j9r', 'Excellent sejour', 'positive');
    

    Rerunning dbt run appends the new record into fct_reviews.

  • To rebuild everything from scratch, perform a full refresh:

    dbt run --full-refresh
    

  • When src models are configured as ephemeral, dbt run output reflects direct compilation into downstream tables:

    23:16:16  1 of 4 START sql table model DEV.dim_hosts_cleansed ............................ [RUN]
    23:16:18  1 of 4 OK created sql table model DEV.dim_hosts_cleansed ....................... [SUCCESS 14111 in 1.93s]
    23:16:18  2 of 4 START sql table model DEV.dim_listings_cleansed ......................... [RUN]
    23:16:20  2 of 4 OK created sql table model DEV.dim_listings_cleansed .................... [SUCCESS 17499 in 2.47s]
    23:16:20  3 of 4 START sql incremental model DEV.fct_reviews ............................. [RUN]
    23:16:23  3 of 4 OK created sql incremental model DEV.fct_reviews ........................ [SUCCESS 0 in 2.37s]
    23:16:23  4 of 4 START sql table model DEV.dim_listings_with_hosts ....................... [RUN]
    23:16:24  4 of 4 OK created sql table model DEV.dim_listings_with_hosts .................. [SUCCESS 17499 in 1.58s]
    23:16:24
    23:16:24  Finished running 1 incremental model, 3 table models in 0 hours 0 minutes and 9.83 seconds (9.83s).
    

  • dbt compile compiles SQL models with Jinja substitutions without deploying to the target data warehouse:

    23:39:49  Running with dbt=1.11.6
    23:39:50  Registered adapter: duckdb=1.9.2
    23:39:50  Found 8 models, 1 seed, 3 sources, 522 macros
    23:39:50
    23:39:50  Concurrency: 1 threads (target='dev')
    

Incremental strategies

Mode Pros Cons
append Simplest; append-only logic No duplicate detection
merge Idempotent; updates existing records Slower; requires a unique key
delete+insert Works for data warehouses lacking MERGE Two-phase operation; requires a unique key
insert+overwrite Fast for partitioned tables Replaces whole partitions

Configure the strategy in the model's config() block:

{{
  config(
    materialized = 'incremental',
    on_schema_change = 'fail',
    incremental_strategy = 'merge',
    unique_key = 'review_id'
  )
}}

Type-2 slowly changing dimensions

Type-2 Slowly Changing Dimensions (SCD Type 2) preserve the historical changes of records over time. dbt automatically injects dbt_valid_from and dbt_valid_to columns. Currently active records have dbt_valid_to set to NULL.

There are two strategies for detecting data changes:

  • Timestamp: A unique_key and an updated_at column define when records change.
  • Check: Compares a specified list of columns (or all columns) against previous values.
  • Snapshots reside in the snapshots/ directory and are defined in .sql or .yml files:

    snapshots:
      - name: scd_raw_listings
        relation: source('airbnb', 'listings')
        config:
          unique_key: id
          strategy: timestamp
          updated_at: updated_at
          hard_deletes: invalidate
    

  • Running dbt snapshot creates or updates the snapshot table with tracking metadata:

    00:04:36  1 of 1 START snapshot DEV scd_raw_listings ..................................... [RUN]
    00:04:40  1 of 1 OK snapshotted DEV.scd_raw_listings ..................................... [SUCCESS 17499 in 3.44s]
    

  • Updating a source record and running dbt snapshot closes the previous record (dbt_valid_to is populated) and inserts a new active version.

Tests

dbt supports two main categories of tests:

  • Unit Tests: Validate model logic against static mock input rows without querying warehouse data.
  • Data Tests: Assert conditions against actual data in target tables. Data tests include:

    • Generic tests: Reusable assertions configured in YAML (e.g. unique, not_null, accepted_values, relationships).
    • Singular tests: Custom SQL queries in tests/ that pass if they return zero rows.
  • Configure tests in models/schema.yml (see Airbnb models schema):

    models:
      - name: dim_listings_cleansed
        description: "Listings dimension"
        columns:
          - name: listing_id
            description: "Listing ID"
            data_tests:
              - not_null
              - unique
    

  • Run tests:

    dbt test --target dev
    # Use --fail-fast (-x) to stop on the first failure:
    dbt test --target dev -x
    

  • For unit tests, define a test block in YAML (e.g. unit_test.yaml), then run:

    dbt test -s mart_fullmoon_reviews
    


Confluent provides two Python libraries for Flink SQL orchestration: dbt-confluent (the dbt adapter for Confluent Cloud Flink) and confluent-sql (a Python DBAPI v2-compatible client for running snapshot and streaming queries).

dbt Confluent adapter architecture with Confluent Cloud REST API access

In Confluent Cloud for Flink, dbt run does not execute batch data processing; instead, it compiles and deploys long-running streaming queries or creates views and tables via the Confluent Cloud Flink API. You run dbt run only when SQL models, DDL definitions, or pipeline configurations change.

For setup instructions, see the Confluent Cloud documentation on dbt. Key notes on dbt init:

  • It creates or updates ~/.dbt/profiles.yml with connection details (Flink compute pool, Kafka cluster/database, API keys).
  • It scaffolds basic project directories. Teams can further refine this structure to enforce naming conventions and modular data product layouts.

  • In the dbt-confluent adapter mapping: a dbt database corresponds to a Flink Catalog (environment), a dbt schema corresponds to a Flink Database (Kafka cluster), and a dbt identifier corresponds to a Flink Table/Topic. The dbname setting in profiles.yml specifies the default Kafka cluster name.

  • Below is an example connection definition in ~/.dbt/profiles.yml:

    cc_flink:
      outputs:
        dev:
          cloud_provider: aws
          cloud_region: us-west-2
          dbname: j9r-kafka
          environment_id: '{{ env_var(''ENVIRONMENT_ID'') }}'
          execution_mode: streaming_query
          flink_api_key: '{{ env_var(''FLINK_API_KEY'') }}'
          flink_api_secret: '{{ env_var(''FLINK_API_SECRET'') }}'
          organization_id: '{{ env_var(''ORGANIZATION_ID'') }}'
          threads: 1
          type: confluent
      target: dev
    
    Note: Some CLI error messages use "schema" when referring to a Kafka cluster or Flink database. When connecting via private networking, provide the endpoint URL (e.g. https://flink.us-east-2.aws.private.confluent.cloud) and omit cloud_provider and cloud_region.

  • The dbt construct mapping for dbt-confluent is as follows:

    dbt Construct Confluent Cloud Flink dbt-confluent Materialization
    view CREATE VIEW ... AS SELECT view
    table CTAS snapshot query streaming_table
    table Streaming query (CREATE TABLE + INSERT INTO) streaming_table
    table Connector-backed source tables or existing Kafka topics streaming_source
    table Materialized table materialized_table
    incremental Not supported in streaming N/A
    ephemeral Not supported N/A
    seeds CREATE TABLE + point-in-time INSERT VALUES seed (default)
  • Model dependencies are declared using {{ ref() }} and {{ source() }}, and dbt executes deployments in topological order.

  • Rerunning dbt run against an existing table, streaming_table, or streaming_source does not recreate it unless modified.
  • Using --full-refresh drops underlying tables/topics and recreates statements. Note: Downstream streaming statements referencing a recreated topic may require restarting if their consumer offsets become invalid.
  • Using model selection with a + suffix (dbt run --select model_name+) deploys the selected model and all its downstream dependents.
  • Resubmitting an append-mode INSERT INTO query from earliest-offset against an existing sink table will create duplicate rows unless deduplicated.
  • Existing Kafka topics created outside of Flink statements can be referenced as sources:
    FROM {{ source('cc_flink', 'cdc.public.customers') }}
    

when declared in models/sources.yml:

version: 2
sources:
  - name: cc_flink
    schema: j9r-kafka
    tables:
      - name: cdc.public.customers
Here, name identifies the dbt source block, schema is the Kafka cluster name, and tables.name is the Kafka topic name.

Organize code repository

Two recommended project layouts:

  1. Kimball architecture by data product:

    crm-analytics
    ├── docs
    ├── IaC
    ├── pipelines
    │   ├── dbt_project.yml
    │   ├── macros
    │   ├── models
    │   │   ├── intermediates
    │   │   │   └── c360
    │   │   ├── marts
    │   │   │   └── c360
    │   │   └── sources
    │   │       └── c360
    │   ├── seeds
    │   └── tests
    ├── sl_dbt.yaml
    └── tools
    

  2. Data product layout with star schema:

    crm-analytics
    ├── docs
    ├── IaC
    ├── pipelines
    │   ├── dbt_project.yml
    │   ├── macros
    │   ├── models
    │   │   └── c360
    │   │       ├── dimensions
    │   │       ├── facts
    │   │       ├── schema.yml
    │   │       └── sources
    │   ├── seeds
    │   └── tests
    ├── sl_dbt.yaml
    └── tools
    

Common project components include:

  • docs: Documentation and architecture diagrams
  • IaC: Terraform configurations for compute pools, service accounts, and API keys
  • pipelines: dbt project configuration, macros, and SQL models
  • sl_dbt.yaml: Metadata configuration for shift-left dbt utilities
  • tools: Helper scripts and migration utilities

Naming convention

  • Establish consistent table and statement naming conventions across environments.
  • Set the statement_name property in model configurations to establish consistent statement names on Confluent Cloud, facilitating automated teardown and recreation during development:
    {{ config(
        materialized = 'streaming_table',
        statement_name = 'dev_crm_customers'
    ) }}
    

Organize table and tests

Project management practices for dbt-based Flink projects are detailed in Data Engineering 101.

Useful commands to remember

  • Compile dbt models to Flink SQL without deploying:

    dbt compile
    
    Compiled statements are located in the target/compiled/ directory.

  • Run a specific model:

    dbt run --select src_listings
    

  • Run all models in a specific directory:
    dbt run --select user_reviews.dimensions
    
  • Inspect downstream impacts:
    dbt ls --select src_listings+
    

Example output from airbnb_streaming:

airbnb_streaming.user_reviews.dimensions.dim_listings_cleansed
airbnb_streaming.user_reviews.dimensions.dim_listings_with_hosts
airbnb_streaming.user_reviews.facts.fct_host_performance
airbnb_streaming.user_reviews.facts.fct_listing_activity
airbnb_streaming.user_reviews.facts.fct_listing_pricing
airbnb_streaming.user_reviews.sources.src_listings

  • List all models upstream of fct_reviews:

    dbt ls --select +fct_reviews
    
    Example output:
    airbnb_streaming.user_reviews.facts.fct_reviews
    airbnb_streaming.user_reviews.sources.src_reviews
    source:airbnb_streaming.raw_reviews.raw_reviews
    

  • List a model and all upstream and downstream dependencies:

    dbt ls --select +fct_reviews+
    
    Example output:
    airbnb_streaming.user_reviews.facts.fct_host_performance
    airbnb_streaming.user_reviews.facts.fct_listing_activity
    airbnb_streaming.user_reviews.facts.fct_review_summary
    airbnb_streaming.user_reviews.facts.fct_reviews
    airbnb_streaming.user_reviews.sources.src_reviews
    source:airbnb_streaming.raw_reviews.raw_reviews
    

  • Generate documentation and view the interactive lineage graph:

    dbt docs generate
    dbt docs serve
    

  • Run unit tests:

    dbt test --select "test_type:unit"
    

Constraints

  • dbt does not automatically cascade changes downstream in streaming environments; --full-refresh applies globally. When modifying intermediate models, explicitly target downstream dependencies using dbt run --select model_name+.
  • Materialized tables (v2 tables) require explicit configuration and lifecycle management.

Testing

See Confluent testing documentation and dbt unit testing.

  • Unit tests can be defined at the Flink model level using mock input rows and asserted output values. Test definitions can be placed in model YAML files or dedicated <model_name>_unit_tests.yml files.
  • Focus unit tests on models containing complex business logic.
  • Include only the specific columns relevant to the logic under test; dbt automatically populates omitted columns with NULL or infers them from schema definitions.
  • When versioning models (e.g., v1, v2), use the versions: tag in unit tests to target specific model versions without breaking legacy tests.

How to

How to define distribution keys for Kafka partitions?
{{
  config(
    materialized = 'streaming_table',
    distributed_by = {
      'columns': ['order_id'],
      'buckets': 4
    },
    with = {
      'changelog.mode': 'upsert',
      'key.format': 'json-registry',
      'value.format': 'json-registry',
      'value.fields-include': 'all',
      'kafka.cleanup-policy': 'compact',
      'kafka.retention.time': '86400000 ms',
      'scan.bounded.mode': 'unbounded',
      'scan.startup.mode': 'earliest-offset'
    }
  )
}}

Distributed keys must match the table's primary key constraint defined in schema.yml:

columns:
  - name: order_id
    data_type: BYTES
    constraints:
      - type: not_null
      - type: primary_key
        expression: not enforced

Or when distributing across composite keys:

constraints:
  - type: primary_key
    columns: [user_id, right_id, __db]
    expression: not enforced

Creating tables with mock seed data for raw sources

To create static test tables in Flink SQL, INSERT INTO ... VALUES is not supported directly in CTAS. Use the VALUES clause in a SELECT statement (see example in basic-sql/cc-dbt):

SELECT emp_id, name, dept_id FROM (VALUES
  (1, 'John Doe', 101),
  (2, 'Jane Smith', 101)
) AS t (emp_id, name, dept_id)
How to define an existing topic as a source?

When raw data already exists in a Kafka topic (such as from a CDC connector), define it in models/sources.yml:

version: 2
sources:
  - name: raw_listings
    schema: j9r-kafka # Kafka cluster name in Confluent Cloud
    tables:
      - name: raw_listings
  - name: raw_hosts
    schema: j9r-kafka
    tables:
      - name: raw_hosts
  - name: raw_reviews
    schema: j9r-kafka
    tables:
      - name: raw_reviews

When models use +materialized: streaming_table, the adapter runs materialization_streaming_table_confluent, validating that column definitions match the target schema.

Declare column names and data types for target tables in a YAML model contract (e.g. src_hosts_models.yml):

models:
  - name: src_hosts
    config:
      contract:
        enforced: false
    columns:
      - name: host_id
        data_type: varchar(2147483647)
      - name: host_name
        data_type: varchar(2147483647)
      - name: is_superhost
        data_type: varchar(2147483647)
      - name: created_at
        data_type: varchar(2147483647)
      - name: updated_at
        data_type: varchar(2147483647)
How to specify a compute pool?

A default compute pool is set in profiles.yml. You can override it per model in YAML:

models:
  - name: my_heavy_model
    config:
      compute_pool: "my-large-pool"

Or inline inside the model's config() block:

{{ config(
    materialized = 'streaming_table',
    compute_pool = 'my-large-pool'
) }}

Seed reference data on Confluent Cloud for Flink

The airbnb_streaming project loads small reference CSVs into Flink tables with dbt seed. The dbt-confluent adapter infers column types from the CSV and issues CREATE TABLE followed by INSERT INTO ... VALUES. Override types in seeds/seeds.yml when inference is too coarse (e.g., mapping date strings to DATE):

version: 2
seeds:
  - name: seed_full_moon_dates
    config:
      alias: raw_full_moon_dates
      column_types:
        full_moon_date: DATE

Set +execution_mode: snapshot on seeds in dbt_project.yml so DDL and INSERT run as point-in-time statements rather than streaming queries. Seeds are limited to 10,000 rows per file:

cd code/dbt/airbnb_streaming
dbt seed --target dev

Optionally run make seed to regenerate seeds.yml column types from CSV headers before seeding.

See another example in the Streamhouse demo.

How to specify table properties?

Use the config() macro with table properties defined in the with dictionary:

{{ config(
    materialized = 'streaming_table',
    with = {
        'changelog.mode': 'upsert'
    }
   )
}}
How to define a primary key for sink/derived tables?

Define primary key constraints in schema.yml for a single column:

columns:
  - name: account_number
    data_type: varchar(2147483647)
    constraints:
      - type: not_null
      - type: primary_key
        expression: "not enforced"

Or as composite primary keys:

columns:
  - name: account_number
    data_type: varchar(255)
  - name: transaction_type
    data_type: varchar(50)
  - name: total_withdrawn
    data_type: decimal(38, 2)
constraints:
  - type: primary_key
    columns: [account_number, transaction_type]
    expression: "NOT ENFORCED"

How to specify a watermark column in schema.yml?

Define a custom table constraint in schema.yml targeting a TIMESTAMP or TIMESTAMP_LTZ column:

models:
  - name: rides_clean
    description: Migrated from dml.rides_clean.sql
    constraints:
      - type: custom
        expression: "WATERMARK FOR pickup_ts AS pickup_ts - INTERVAL '5' SECOND"
    columns:
      - name: driver_id
        data_type: STRING
        constraints:
          - type: not_null
          - type: primary_key
            expression: "not enforced"
      - name: pickup_ts
        data_type: TIMESTAMP(3)

How to define a materialized table?

Configure materialized = 'materialized_table' in the model's config() block:

{{ config(
    materialized       = 'materialized_table',
    freshness_interval = "INTERVAL '1' MINUTE",
    distributed_by     = "order_id",
    start_mode         = 'RESUME_OR_FROM_BEGINNING',
    with               = {
        'key.format': 'avro-registry',
        'value.format': 'avro-registry'
    }
  )
}}

See dbt-confluent materializations reference.

How to define columns that conflict with SQL reserved keywords?

In SQL, reserved keywords are escaped with backticks. In a dbt schema file, set quote: true:

columns:
  - name: value
    data_type: VARCHAR
    quote: true
How to define a User-Defined Function (UDF)?

Place the JAR artifact in a udfs/ directory and register the artifact and function in your dbt configuration (see Confluent UDF documentation). In the models/functions folder adds a sql to define the artifact

  {{ config(
      language='java',
      artifact_path='udfs/tshirt-sizing.jar',
      path='com.example.my.TShirtSizingIsSmaller',
  ) }}

The to reference the function in a SQL model, use the function macro:

  select {{ function('is_smaller') }}(requested_size, in_stock_size) as needs_upsize
  from {{ ref('orders') }}

Flink functions are immutable, and an artifact cannot gain new versions in-place. Replacing a function package requires uploading the new artifact, dropping the old function, and creating the new function definition.

How to alter dependent source tables before model execution?

If a source table needs modified table properties before query execution (such as switching changelog mode), use pre_hook in the config() block:

{{ config(
  materialized = 'streaming_table',
  pre_hook = [
      "ALTER TABLE {{ source('cdc', 'customers') }} SET ('changelog.mode' = 'append')",
      "ALTER TABLE {{ source('cdc', 'customers') }} SET ('value.format' = 'avro-registry')"
  ]
) }}

Enabling Confluent Tableflow

Add a tableflow configuration to a model, and the adapter automatically materializes the topic into an Iceberg and/or Delta table using Confluent-managed storage or customer-owned cloud storage (S3, ADLS, or GCS). See Confluent dbt reference documentation.

Private networking / using custom endpoints

For private networking, specify the endpoint parameter in profiles.yml and omit cloud_provider and cloud_region:

cc_flink:
  outputs:
    dev:
      endpoint: https://flink.us-east-2.aws.private.confluent.cloud
      compute_pool_id: lfcp-11p88z
      dbname: j9r-kafka
      environment_id: '{{ env_var(''ENVIRONMENT_ID'') }}'
      flink_api_key: '{{ env_var(''FLINK_API_KEY'') }}'
      flink_api_secret: '{{ env_var(''FLINK_API_SECRET'') }}'
      organization_id: '{{ env_var(''ORGANIZATION_ID'') }}'
      statement_label: dbt-confluent
      statement_name_prefix: dbt-
      threads: 1
      type: confluent
  target: dev

How to resolve the NullConverter error in dbt seed?

The error NullConverter cannot convert Python None to statement string directly. Use AnnotatedNull to specify the desired SQL type for NULL parameters occurs during dbt seed when an empty CSV cell represents NULL and dbt cannot infer the SQL column type. To resolve this, explicitly define column data types in seeds/seeds.yml:

version: 2
seeds:
  - name: my_seed_data
    config:
      column_types:
        nullable_column: VARCHAR
Resolving duplicate entry error in schema.yml (stale parse cache)

If dbt reports:

dbt found two schema.yml entries for the same resource named <resource>. Resources and their associated columns may only be described a single time.
This is typically caused by a stale partial-parse cache rather than an actual duplicate in source files. Clear the dbt cache and recompile:

rm target/partial_parse.msgpack
dbt compile
Resolving unquoted reserved keywords in generated validation SQL

When every column in schema.yml declares a data_type with constraints, dbt treats the model as contract-enforced and runs default__get_empty_schema_sql to validate types before submitting the real DML.

If a column name conflicts with a reserved SQL keyword (e.g. comment), ensure quote: true is set in schema.yml:

columns:
  - name: comment
    data_type: VARCHAR
    quote: true

Running dbt-confluent in dbt Cloud

dbt Labs is developing dbt Core 2.0 / Fusion in Rust for dbt Cloud. The dbt-confluent adapter is currently built on dbt Core 1.x as a Python library. Future cloud-native integration will leverage an ADBC driver.

Added tools

The flink-tools-for-agents/tools repository includes useful automation utilities for dbt Confluent projects:

Tool Purpose Usage
sl_dbt.py Manage shift-left streaming projects from batch to dbt and Flink SQL sl_dbt init <project_root>, sl_dbt add-data-product <data_product>, sl_dbt.py add-table crm-analytics src_customers c360 --table-type dim
sql_to_dbt_yaml.py Parse a dbt SQL model file and emit ready-to-paste models: YAML contracts, resolving columns and types from upstream definitions uv run sql_to_dbt_yaml.py ../airbnb_streaming/models/user_reviews/dimensions/dim_listings_with_hosts.sql
flink_dbt_migrate Convert standalone Flink SQL DDL/DML/CTAS scripts into dbt streaming models flink_dbt_migrate.migrate_dml_to_dbt ../cc-flink/dml.enriched_orders.sql ../cc_dbt/models/intermediates/enriched_orders
statement_management.py Helper script to inspect, stop, and clean up statements created by dbt python statement_management.py --action stop-all

Sources of Information