dbt-starrocks
This project is under development.
The dbt-starrocks package contains all the code to enable dbt to work with StarRocks.
- Requires StarRocks version 2.5.0 or higher
- version 3.4.x is recommended
- StarRocks versions 2.4 and below are no longer supported
Installation
This plugin can be installed via pip:
$ pip install dbt-starrocks
Supported features
| StarRocks <= 2.5 | StarRocks 2.5 ~ 3.1 | StarRocks >= 3.1 | StarRocks >= 3.4 | Feature |
|---|---|---|---|---|
| ✅ | ✅ | ✅ | ✅ | Table materialization |
| ✅ | ✅ | ✅ | ✅ | View materialization |
| ❌ | ❌ | ✅ | ✅ | Materialized View materialization |
| ❌ | ✅ | ✅ | ✅ | Incremental materialization |
| ❌ | ✅ | ✅ | ✅ | Primary Key Model |
| ✅ | ✅ | ✅ | ✅ | Sources |
| ✅ | ✅ | ✅ | ✅ | Custom data tests |
| ✅ | ✅ | ✅ | ✅ | Docs generate |
| ❌ | ❌ | ✅ | ✅ | Expression Partition |
| ❌ | ❌ | ❌ | ❌ | Kafka |
| ❌ | ❌ | ❌ | ✅ | Dynamic Overwrite |
| ❌ | *4 | *4 | ✅ | Submit task |
| ❌ | ✅ | ✅ | ✅ | Microbatch (Insert Overwrite) |
| ❌ | ❌ | ❌ | ✅ | Microbatch (Dynamic Overwrite) |
| ✅ | ✅ | ✅ | ✅ | Model contracts *7 |
Notice
- When StarRocks Version < 2.5,
Create table ascan only set engine='OLAP' and table_type='DUPLICATE' - When StarRocks Version >= 2.5,
Create table assupports table_type='PRIMARY' - When StarRocks Version < 3.1 distributed_by is required
- Verify the specific
submit tasksupport for your version, see SUBMIT TASK. - Views: when a view's SQL is unchanged,
dbt runissues no DDL on the view, leaving it in place (the run log notesskip <view>, and the model still completes as a successful no-op). This avoids deactivating dependent materialized views, which StarRocks does whenever a base view is recreated, even with identical SQL. table_typeis case-insensitive —'primary','PRIMARY','Primary'are all accepted.- Column names and data types are checked; of the constraint types, only
primary_keyis applied (not enforced), and all others are ignored. See Model Contracts and Constraints.
Profile Configuration
Example entry for profiles.yml:
starrocks:
target: dev
outputs:
dev:
type: starrocks
host: localhost
port: 9030
catalog: default_catalog
schema: analytics
username: your_starrocks_username
password: your_starrocks_password
| Option | Description | Required? | Example |
|---|---|---|---|
| type | The specific adapter to use | Required | starrocks |
| host | The hostname to connect to | Required | 192.168.100.28 |
| port | The port to use | Required | 9030 |
| catalog | Specify the catalog to build models into | Optional | default_catalog |
| schema | Specify the schema (database in StarRocks) to build models into | Required | analytics |
| username | The username to use to connect to the server | Required | dbt_admin |
| password | The password to use for authenticating to the server | Required | correct-horse-battery-staple |
| version | Let Plugin try to go to a compatible starrocks version | Optional | 3.1.0 |
| use_pure | set to "true" to use C extensions | Optional | true |
| is_async | "true" to submit suitable tasks as etl tasks. | Optional | true |
| async_query_timeout | Sets the query_timeout value when submitting a task to StarRocks |
Optional | 300 |
| poll_interval | Base delay in seconds between task status polls | Optional | 1 |
| poll_max_delay | Maximum delay cap in seconds for task polling | Optional | 600 |
| poll_factor | Growth multiplier for exponential backoff between polls | Optional | 2.0 |
| auth_plugin | MySQL client authentication plugin to use | Optional | authentication_openid_connect_client |
| openid_token_file | Path to a file holding an OpenID Connect ID token, read by the authentication_openid_connect_client plugin |
Optional | /tmp/starrocks.jwt |
| ssl_ca | CA bundle to trust for the FE's certificate, on top of the system store | Optional | /path/to/private-ca.pem |
| ssl_verify_cert | Verify the FE's certificate chain | Optional | true |
| ssl_verify_identity | Also check that the certificate matches host |
Optional | true |
To log in with an OpenID Connect ID token through a StarRocks JWT security integration, set auth_plugin to authentication_openid_connect_client and point openid_token_file at a file holding the token. This needs mysql-connector-python 9.1 or later. password is not used.
The plugin refuses to send the token over a plaintext connection, so the FE needs SSL enabled. Without ssl_verify_cert, mysql-connector-python encrypts the connection but does not verify the FE's certificate, so anyone who can impersonate the FE can capture and replay the token. Set ssl_verify_cert: true, and ssl_verify_identity: true when host matches a name on the certificate. With use_pure, the connector always trusts the system CA store and ssl_ca adds a private CA to it. With threads above 1, set use_pure: "true": concurrent logins through the C extension's plugin crashed dbt in our testing (malloc(): unaligned tcache chunk detected), and the pure-Python plugin did not.
username: your_starrocks_username
password: ''
auth_plugin: authentication_openid_connect_client
openid_token_file: /path/to/id_token.jwt
ssl_verify_cert: true
ssl_verify_identity: true
use_pure: "true"
More details about setting use_pure and other connection arguments here
Example
dbt seed properties(yml):
Complete configuration:
models:
materialized: table // table, view, materialized_view or incremental
engine: 'OLAP'
keys: ['id', 'name', 'some_date']
table_type: 'PRIMARY' // PRIMARY or DUPLICATE or UNIQUE
distributed_by: ['id']
buckets: 3 // leave empty for auto bucketing
indexs=[{ 'columns': 'idx_column' }]
partition_by: ['some_date']
partition_by_init: ["PARTITION p1 VALUES [('1971-01-01 00:00:00'), ('1991-01-01 00:00:00')),PARTITION p1972 VALUES [('1991-01-01 00:00:00'), ('1999-01-01 00:00:00'))"]
// RANGE, LIST, or Expr partition types should be used in conjunction with partition_by configuration
// Expr partition type requires an expression (e.g., date_trunc) specified in partition_by
order_by: ['some_column'] // only for PRIMARY table_type
partition_type: 'RANGE' // RANGE or LIST or Expr Need to be used in combination with partition_by configuration
properties: {"replication_num":"1", "in_memory": "true"}
refresh_method: 'async' // only for materialized view default manual
on_view_exists: 'replace' // only for view: use CREATE OR REPLACE VIEW instead of DROP + CREATE
on_table_exists: 'swap' // only for table: build <name>__dbt_tmp and ALTER TABLE ... SWAP WITH it, instead of DROP + CREATE. Supported values: ['replace' (default), 'swap', 'append', 'ignore']
// For 'materialized=incremental'
incremental_strategy: 'merge' // Supported values: ['default', 'append', 'merge', 'insert_overwrite', 'dynamic_overwrite', 'microbatch'] ('default' will be deprecated)
unique_key: ['id'] // Makes the table PRIMARY KEY, as 'merge' requires; not allowed with 'append'
// 'insert_overwrite' and 'dynamic_overwrite' require version >= 3.4
// For 'materialized=incremental' and 'incremental_strategy=microbatch'
event_time: 'some_timestamp_column' // The column name of the event time
begin: '2025-01-01' // The start time of the incremental data
lookback: 1 // The lookback time of the each incremental run
batch_size: 'day' // The batch size. Supported values ['year', 'month', 'day', 'hour']
microbatch_use_dynamic_overwrite: true // Whether to use dynamic_overwrite in version >= 3.4
dbt run config:
Example configuration:
{{ config(materialized='view') }}
{{ config(materialized='view', on_view_exists='replace') }}
{{ config(materialized='table', engine='OLAP', buckets=32, distributed_by=['id']) }}
{{ config(materialized='table', on_table_exists='swap') }}
{{ config(materialized='table', indexs=[{ 'columns': 'idx_column' }]) }}
{{ config(materialized='table', partition_by=['date_trunc("day", first_order)'], partition_type='Expr') }}
{{ config(materialized='table', table_type='PRIMARY', keys=['customer_id'], order_by=['first_name', 'last_name']) }}
{{ config(materialized='incremental', table_type='PRIMARY', keys=['id'], engine='OLAP', buckets=32, distributed_by=['id']) }}
{{ config(materialized='incremental', incremental_strategy='merge', unique_key=['id']) }}
{{ config(materialized='incremental', incremental_strategy='append') }}
{{ config(materialized='incremental', partition_by=['my_partition_key'], partition_type='Expr', incremental_strategy='dynamic_overwrite') }}
{{ config(materialized='incremental', partition_by=['my_partition_key'], partition_type='Expr', incremental_strategy='microbatch', event_time='report_day', begin='2025-01-01', lookback=1, batch_size='day') }}
{{ config(materialized='incremental', partition_by=['my_partition_key'], partition_type='Expr', incremental_strategy='microbatch', event_time='report_day', begin='2025-01-01', lookback=1, batch_size='day', microbatch_use_dynamic_overwrite=true) }}
{{ config(materialized='materialized_view') }}
{{ config(materialized='materialized_view', properties={"storage_medium":"SSD"}) }}
{{ config(materialized='materialized_view', refresh_method="ASYNC START('2022-09-01 10:00:00') EVERY (interval 1 day)") }}
For materialized view only support partition_by、buckets、distributed_by、properties、refresh_method configuration.
Read From Catalog
First you need to add this catalog to starrocks. The following is an example of hive.
CREATE EXTERNAL CATALOG `hive_catalog`
PROPERTIES (
"hive.metastore.uris" = "thrift://127.0.0.1:8087",
"type"="hive"
);
How to add other types of catalogs can be found in the documentation. https://docs.starrocks.io/en-us/latest/data_source/catalog/catalog_overview Then write the sources.yaml file.
sources:
- name: external_example
schema: hive_catalog.hive_db
tables:
- name: hive_table_name
Finally, you might use below marco quote
{{ source('external_example', 'hive_table_name') }}
Write To Catalog
Set catalog in a model's config, or in the profile, to build it inside an external catalog.
database names the database in that catalog. Without it, table and incremental models
use the model's resolved schema, as models in default_catalog do: the profile's schema, or
<schema>_<custom> when the model sets a custom schema with schema or +schema.
{{ config(materialized='table', catalog='iceberg_catalog', database='iceberg_db') }}
{{ config(materialized='incremental', incremental_strategy='dynamic_overwrite',
catalog='iceberg_catalog', database='iceberg_db',
partition_by=['day(`modified_at`)']) }}
{{ config(materialized='table', catalog='iceberg_catalog', schema='marts') }}
The table name comes from the model's file name (or its alias), not from database.
A nested Iceberg namespace is one dotted database name, e.g. database='bronze.sales'. On an
Iceberg REST catalog, set 'iceberg.catalog.rest.nested-namespace-enabled'='true' when you
create the catalog. It defaults to false, which hides nested namespaces from
information_schema: dbt can't see tables that already exist in them, and the next run fails
with Table ... already exists.
Only partition_by, partition_type (defaulting to Expr), partition_by_init and
properties are applied to external tables. table_type, keys, distributed_by,
buckets and order_by describe OLAP tables and are ignored here — Iceberg rejects key
clauses outright.
Because there are no keys, unique_key cannot deduplicate an external-catalog incremental
model: INSERT INTO appends. Replace partitions instead, with insert_overwrite or
dynamic_overwrite. On Iceberg both replace only the partitions the query produced and
leave the others in place, so they behave alike there; the difference between them applies
to OLAP tables. Row-level unique_key semantics would need DELETE on Iceberg, which
StarRocks only writes position delete files for from 4.1 onwards.
Incremental strategies
The incremental_strategy config supports the following values:
append: PlainINSERT INTO. Rows are added; nothing is deduplicated or replaced. Requires a DUPLICATE KEY table, sounique_keycannot be set.merge: Upsert on the table's PRIMARY KEY. Requires a PRIMARY KEY table: setunique_key,table_type='PRIMARY'withkeys, or an enforced contract with aprimary_keyconstraint.insert_overwrite: Appliesoverwritewithdynamic_overwrite = false(StarRocks >= 3.4).dynamic_overwrite: Appliesoverwritewithdynamic_overwrite = true(StarRocks >= 3.4).microbatch: Processes the model in time-based batches; see the microbatch configs above.default(or omitted): Behaviour depends on the table type. Will be deprecated in a future release; see below.
append and merge check the existing table's key type on every incremental run. If the
model's config changed since the table was built (for example, unique_key was added),
the run fails until you rebuild the table with dbt run --full-refresh.
How merge works
StarRocks has no MERGE statement. Instead, setting unique_key on an incremental model
builds the target as a PRIMARY KEY table
keyed on those columns, where an ordinary INSERT INTO is an upsert: matching keys are
replaced, new keys are inserted.
How this differs from merge on other dbt adapters:
- Rows are matched on the table's PRIMARY KEY, which is set when the table is created.
Changing
unique_key(orkeys) on an existing model does not change it: incremental runs keep upserting on the old key, so rows that differ only in a newly added key column overwrite each other. Rebuild the table withdbt run --full-refresh, or migrate its key outside dbt, whenever the key changes. - If the new data contains several rows with the same key, one of them is kept and the rest
are dropped without an error, where a
MERGEon Snowflake, BigQuery or Postgres fails. Deduplicate in the model if that matters. - The columns the model produces are written. Columns the table has but the model no longer
produces (for example after
on_schema_changechanges) keep their existing values on StarRocks >= 3.3.1, and are reset to their defaults on earlier versions.merge_update_columns,merge_exclude_columnsandincremental_predicatesneed aMERGEstatement, which StarRocks does not have, so they raise an error rather than being silently ignored. - On a partitioned table, StarRocks requires the partition column to be part of the primary
key, so
unique_keymust include yourpartition_bycolumn. - An existing UNIQUE KEY table, which dbt cannot create but may have been created outside
it, is accepted too: an
INSERTreplaces its rows by key in the same way.
merge is not supported for models in an external catalog, whose tables have no PRIMARY KEY.
default will be deprecated
default, which is also what you get when incremental_strategy is not set, runs a plain
INSERT INTO whose effect depends on the table type: it upserts into a PRIMARY KEY table and
appends to a DUPLICATE KEY table. It is still fully supported, and each run logs a notice
that it will be deprecated in a future release. To prepare, switch to the explicit strategy
for your table, which runs the same SQL:
| Table built by the model | Use |
|---|---|
PRIMARY KEY (unique_key, table_type='PRIMARY' with keys, or a contract primary_key) |
merge |
| DUPLICATE KEY (the default table type) | append |
| External catalog | append |
For more details on the different behaviors, see StarRocks' documentation for INSERT.
Model Contracts and Constraints
dbt-starrocks supports dbt model contracts for table, incremental and view models. An enforced contract does two things:
- Column and type check. Before building, dbt checks that the model's query returns exactly the columns declared in YAML, with matching data types, and fails the build otherwise. For example, a column declared
data_type: intfails the build if the query returns it asbigintorvarchar. primary_keyonly. Of dbt's constraint types, onlyprimary_keyhas an effect: it makes the table aPRIMARY KEYtable (see Deriving table type from constraints). All other constraints, includingnot_null, are ignored with a warning.
The contract validates the model's query, not the table built from it. Tables are created with CREATE TABLE ... AS SELECT, so column types come from StarRocks' type inference rather than the YAML:
| Aspect | Checked by the contract? | What the built table gets |
|---|---|---|
| Column names | Yes. Missing, extra, or renamed columns fail the build | Same as the query |
Base type (int vs bigint, varchar vs int) |
Yes | Same as the query, except float/double below |
varchar length |
No | The query expression's length; string becomes VARCHAR(65533) and unbounded expressions such as concat() become VARCHAR(1048576) |
decimal precision and scale |
No | The query expression's precision and scale |
float / double |
Yes, against the query | Converted to DECIMAL(38, 9) by CTAS. A model declaring double passes the contract but produces a decimal column |
| Nullability | No | Follows the query (constant expressions are NOT NULL); primary key columns are always NOT NULL |
Note: To control a column's exact type,
castit in the model'sSELECT(for examplecast(name as varchar(255))). This does not help withfloat/double, which CTAS always stores asDECIMAL(38, 9).
Constraint support (only primary_key changes the table):
| Constraint type | Support | Behavior |
|---|---|---|
primary_key |
Not enforced | Sets the table type to PRIMARY KEY and derives key columns |
not_null |
Not supported | Ignored; column nullability follows the query |
unique |
Not supported | Ignored; table falls back to DUPLICATE KEY |
check |
Not supported | Ignored |
foreign_key |
Not supported | Ignored |
custom |
Not supported | Ignored (no warning is logged) |
Note:
primary_keyis not enforced because StarRocksPRIMARY KEYtables use last-write-wins deduplication: a duplicate key replaces the existing row instead of failing the build. Primary key columns are alwaysNOT NULL.
Note:
not_nullis not supported because tables are built withCREATE TABLE ... AS SELECT, which cannot declare column nullability.
dbt logs a warning for each constraint that is not supported or not enforced. Set warn_unsupported: false or warn_unenforced: false on the constraint to silence it. Views check the contract but do not apply constraints.
Deriving table type from constraints
When contract.enforced: true is set and no explicit keys config is provided, the adapter inspects the model's constraints and automatically configures the table:
- A
primary_keyconstraint on one or more columns creates aPRIMARY KEYtable keyed on those columns. - A model-level
primary_keyconstraint (with acolumnslist) takes priority over column-level constraints. - Explicit
keysconfig always wins over constraints, as does an explicittable_typeother thanPRIMARY(for exampletable_type='DUPLICATE'). - With
table_type='PRIMARY'and nokeys, the key columns are taken from theprimary_keyconstraint. - Primary key columns must come first in the model's
SELECT, in the same order as the key. StarRocks rejects the table otherwise (Key columns must be the first few columns of the schema).
Column-level primary key:
models:
- name: my_model
config:
contract:
enforced: true
columns:
- name: id
data_type: int
constraints:
- type: primary_key
- name: name
data_type: varchar(255)
Model-level primary key (multi-column):
models:
- name: my_model
config:
contract:
enforced: true
constraints:
- type: primary_key
columns: [tenant_id, id]
columns:
- name: tenant_id
data_type: int
- name: id
data_type: int
- name: name
data_type: varchar(255)
Both examples above produce a PRIMARY KEY(id) (or PRIMARY KEY(tenant_id, id)) table without needing table_type='PRIMARY' or keys=[...] in the model config.
Submittable ETL tasks
The implementation of the submittable etl is located in the
impl.pyfile.
Setting is_async: true in your profiles.yml will enable submitting suitable ETL tasks using the submit task feature of StarRocks.
This will be automatically wrapped around any statement that supports submission. Setting this manually is currently not supported by the adapter.
The following statements will be submitted automatically:
CREATE AS ... SELECTINSERT INTO|OVERWRITECACHE SELECT ...
Task Polling
Once the task has been submitted, the adapter will periodically poll StarRocks' information_schema.task_runs to retrieve the task status.
The polling is implemented using a configurable exponential backoff. The adapter's connection to the StarRocks' cluster will not be maintained during the waiting period. It will be re-opened right before the next status polling phase.
The polling delay is calculated as: min(poll_max_delay, poll_interval * (poll_factor ^ attempt))
| Option | Description | Default |
|---|---|---|
| poll_interval | Base delay in seconds between polls | 1 |
| poll_max_delay | Maximum delay cap in seconds | 600 |
| poll_factor | Growth multiplier for exponential backoff | 2.0 |
For example, with poll_interval: 5, poll_factor: 1.5, poll_max_delay: 60:
| Attempt | Delay |
|---|---|
| 1 | 7.5s |
| 2 | 11.25s |
| 3 | 16.9s |
| 4 | 25.3s |
| 5 | 38s |
| 6 | 57s |
| 7+ | 60s (capped) |
Compared to defaults (poll_interval: 1, poll_factor: 2.0, poll_max_delay: 600):
| Attempt | Delay |
|---|---|
| 1 | 2s |
| 2 | 4s |
| 3 | 8s |
| 4 | 16s |
| 5 | 32s |
| 6 | 64s |
| 7 | 128s |
| 8 | 256s |
| 9 | 512s |
| 10+ | 600s (capped) |
Controlling the task timeout
Using the async_query_timeout property in the profiles.yml will control the value of the query_timeout when submitting task.
It's going to be injected in the SQL query submitted to StarRocks:
submit /*+set_var(query_timeout={async_query_timeout})*/ task ...
Example profiles.yml configuration
my_profile:
target: dev
outputs:
dev:
type: starrocks
host: host
port: 9030
schema: schema
username: username
password: password
is_async: true
async_query_timeout: 3600 # 1 hour
poll_interval: 5
poll_max_delay: 60
poll_factor: 1.5
Test Adapter
Prepare env: install dev requirements and run StarRocks docker image
pip install -r dev_requirements.txt
docker run -p 9030:9030 starrocks/allin1-ubuntu:3.5-latest
Run the following
python3 -m pytest tests/functional
consult the project
Contributing
We welcome you to contribute to dbt-starrocks. Please see the Contributing Guide for more information.
Metadata
Release files for dbt-starrocks 1.12.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dbt_starrocks-1.12.3.tar.gz | 48.9 kB | Without provenance | Details for dbt_starrocks-1.12.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dbt_starrocks-1.12.3-py3-none-any.whl | Python 3 | none | any | Details for dbt_starrocks-1.12.3-py3-none-any.whl |
Total release size: 107.0 kB
Release files / dbt_starrocks-1.12.3.tar.gz
| Download URL | dbt_starrocks-1.12.3.tar.gz |
|---|---|
| Size | 48.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
dc834350c8b388f838c3e80a41b9524419d697ffe310854c584e8b299c182a8d
|
|
BLAKE2b-256 checksum How to use checksums |
d610929d7af6abc14cabcf73fea35842d38929bf33684cefaacfbf17b4cd50d5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / dbt_starrocks-1.12.3-py3-none-any.whl
| Download URL | dbt_starrocks-1.12.3-py3-none-any.whl |
|---|---|
| Size | 58.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b350b0605f89123dacd0e9c6531818d8bf46ace281ea6faf53083d9063c29eb7
|
|
BLAKE2b-256 checksum How to use checksums |
a646eca357be419dbf3cd1f45ef7972cb461fac694986638a37f25504ff0d39f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for dbt-starrocks 1.12.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.