Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .github/scripts/wait-for-db.sh
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,52 @@ starrocks_ready() {
docker exec -i starrocks-fe mysql -h127.0.0.1 -P9030 -uroot -e "ADMIN SET frontend config ('default_replication_num' = '1');"
}

doris_ready() {
local hostname="${DOCKER_HOSTNAME:-localhost}"
echo "Probing '$hostname' on port 9030"
local deadline=$((SECONDS + 180))
until nc -z "$hostname" 9030; do
if [ "$SECONDS" -ge "$deadline" ]; then
echo "ERROR: Timed out waiting for Doris FE port 9030"
docker logs --tail 50 doris-fe || true
exit 1
fi
sleep 1
done

echo "Waiting for Doris FE MySQL endpoint..."
until docker exec doris-fe mysql -h127.0.0.1 -P9030 -uroot -e "SHOW FRONTENDS\G" 2>/dev/null | grep -q "Alive: true"; do
if [ "$SECONDS" -ge "$deadline" ]; then
echo "ERROR: Timed out waiting for Doris FE readiness"
docker logs --tail 50 doris-fe || true
exit 1
fi
sleep 2
done

docker exec doris-fe mysql -h127.0.0.1 -P9030 -uroot -e 'ALTER SYSTEM ADD BACKEND "172.30.80.3:9050";' || true

echo "Checking for 1 alive Doris backend..."
deadline=$((SECONDS + 180))
while true; do
ALIVE_BACKENDS=$(docker exec doris-fe mysql -h127.0.0.1 -P9030 -uroot -e "SHOW BACKENDS\G" 2>/dev/null | grep -c "^ *Alive: true *$" || true)
if [[ "$ALIVE_BACKENDS" =~ ^[0-9]+$ ]] && [ "$ALIVE_BACKENDS" -ge 1 ]; then
echo "Doris has $ALIVE_BACKENDS alive backend(s)"
break
fi
if [ "$SECONDS" -ge "$deadline" ]; then
echo "ERROR: Timed out waiting for an alive Doris backend"
docker logs --tail 50 doris-fe || true
docker logs --tail 50 doris-be || true
exit 1
fi
echo "Waiting for Doris backend to become alive..."
sleep 3
done

docker exec doris-fe mysql -h127.0.0.1 -P9030 -uroot -e 'SELECT 1' >/dev/null
}

trino_ready() {
# Trino has a built-in healthcheck script, just call that
docker compose -f tests/core/engine_adapter/integration/docker/compose.trino.yaml exec trino /bin/bash -c '/usr/lib/trino/bin/health-check'
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ jobs:
clickhouse-datalake,
risingwave,
starrocks,
doris,
]
env:
PYTEST_XDIST_AUTO_NUM_WORKERS: 2
Expand Down
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ engine-%-install:
$(PIP) install -e ".[dev,web,slack,lsp,${*}]" ./examples/custom_materializations

engine-docker-%-up:
@if [ "${*}" = "doris" ]; then $(MAKE) doris-host-setup; fi
docker compose -f ./tests/core/engine_adapter/integration/docker/compose.${*}.yaml up -d
./.github/scripts/wait-for-db.sh ${*}

Expand Down Expand Up @@ -239,6 +240,20 @@ starrocks-test: engine-starrocks-up
db2-test: engine-db2-up
pytest -n auto -m "db2" --reruns 3 --junitxml=test-results/junit-db2.xml

doris-host-setup:
@if [ "$$(uname -s)" = "Linux" ]; then \
current=$$(sysctl -n vm.max_map_count 2>/dev/null || echo 0); \
if [ "$$current" -lt 2000000 ]; then \
sudo -n sysctl -w vm.max_map_count=2000000 >/dev/null 2>&1 || { \
echo "ERROR: vm.max_map_count is $$current (< 2000000); run 'sudo sysctl -w vm.max_map_count=2000000' before starting Doris."; \
exit 1; \
}; \
fi; \
fi

doris-test: doris-host-setup engine-doris-up
pytest -n auto -m "doris" --reruns 3 --junitxml=test-results/junit-doris.xml

#################
# Cloud Engines #
#################
Expand Down
1 change: 1 addition & 0 deletions docs/guides/connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ default_gateway: local_db
* [ClickHouse](../integrations/engines/clickhouse.md)
* [Databricks](../integrations/engines/databricks.md)
* [Db2](../integrations/engines/db2.md)
* [Doris](../integrations/engines/doris.md)
* [DuckDB](../integrations/engines/duckdb.md)
* [Fabric](../integrations/engines/fabric.md)
* [MotherDuck](../integrations/engines/motherduck.md)
Expand Down
1 change: 1 addition & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Other extras are required to use specific SQL engines, like Bigquery or Postgres
| Bigquery | `pip install "sqlmesh[bigquery]"` |
| ClickHouse | `pip install "sqlmesh[clickhouse]"` |
| Databricks | `pip install "sqlmesh[databricks]"` |
| Doris | `pip install "sqlmesh[doris]"` |
| Fabric | `pip install "sqlmesh[fabric]"` |
| GCP Postgres | `pip install "sqlmesh[gcppostgres]"` |
| MS SQL Server | `pip install "sqlmesh[mssql]"` |
Expand Down
127 changes: 127 additions & 0 deletions docs/integrations/engines/doris.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Apache Doris

!!! info
The Apache Doris engine adapter is a community contribution. Due to this, only limited community support is available.

## Overview

[Apache Doris](https://doris.apache.org/) is an MPP analytical database based on columnar storage that supports real-time and batch analytics using the MySQL wire protocol.

SQLMesh connects to Apache Doris using `pymysql` and supports standard analytical workflows on internal OLAP tables (`DUPLICATE KEY` and `UNIQUE KEY` Merge-on-Write).

## Prerequisites

* Install SQLMesh with the Apache Doris extra:

```bash
pip install "sqlmesh[doris]"
```

* Configure a separate `state_connection` backend (Apache Doris is not supported as a SQLMesh `state_connection`; use DuckDB, Postgres, or MySQL instead).

## Connection Configuration Example

```yaml linenums="1" hl_lines="2 4-8 12-14"
gateways:
doris:
connection:
type: doris
host: doris-fe # Frontend (FE) node address
port: 9030 # MySQL query port (default: 9030)
user: root
password: your_password
database: your_database
# Optional PyMySQL settings:
# charset: utf8mb4
# connect_timeout: 10
state_connection:
type: duckdb
database: ./sqlmesh_state.db

default_gateway: doris

model_defaults:
dialect: doris
```

### Connection Options

| Option | Description | Type | Default | Required |
| ------------------ | ----------------------------------------------------------- | :----: | ------- | :------: |
| `type` | Engine type name — must be `doris` | string | — | Y |
| `host` | Hostname of the Doris FE node | string | — | Y |
| `user` | Username for authentication | string | — | Y |
| `password` | Password for authentication | string | `""` | N |
| `port` | Query port of the Doris FE node | int | `9030` | N |
| `database` | Default database name | string | `None` | N |
| `charset` | Character set for the connection | string | `None` | N |
| `collation` | Collation for the connection | string | `None` | N |
| `ssl_disabled` | Whether to disable SSL | bool | `None` | N |
| `connect_timeout` | Connection timeout in seconds | int | `10` | N |
| `concurrent_tasks` | Maximum concurrent tasks using this connection | int | `4` | N |

### Single-Node Setup Note

On single-BE clusters (such as local Docker environments), Doris defaults to a replication factor of 3. Set `force_olap_table_replication_num = 1` in `fe.conf`, or specify `replication_num = '1'` in `physical_properties`.

## Supported Model Kinds & Table Types

| Model Kind | Default Table Type | Notes |
| --------------------------- | ------------------ | ----------------------------------------------------------------------------------------- |
| `FULL` | `DUPLICATE KEY` | Supports optional `duplicate_key` or `unique_key` in `physical_properties`. |
| `VIEW` | — | Supports table and column comments in `CREATE OR REPLACE VIEW`. |
| `SEED` | `DUPLICATE KEY` | Loaded via batched `INSERT` statements. |
| `INCREMENTAL_BY_UNIQUE_KEY` | `UNIQUE KEY` | Auto-promotes `unique_key` to a Doris `UNIQUE KEY` Merge-on-Write table (`DELETE`+`INSERT`). |
| `INCREMENTAL_BY_TIME_RANGE` | `UNIQUE KEY` | Requires `physical_properties (unique_key = (...))`. Uses `DELETE` + `INSERT`. |
| `SCD_TYPE_2_BY_TIME` | `UNIQUE KEY` | Requires `physical_properties (unique_key = (...))` including `valid_from`. |
| `SCD_TYPE_2_BY_COLUMN` | `UNIQUE KEY` | Requires `physical_properties (unique_key = (...))` including `valid_from`. |

### Why Incremental Models Require `UNIQUE KEY`

Apache Doris rejects subquery `DELETE` statements on `DUPLICATE KEY` tables. To ensure deletes generated by incremental and SCD Type 2 models execute cleanly, SQLMesh enforces `UNIQUE KEY` (with `enable_unique_key_merge_on_write = 'true'` and `DISTRIBUTED BY HASH(<key>) BUCKETS AUTO` by default) for incremental model kinds.

- For `INCREMENTAL_BY_UNIQUE_KEY`, SQLMesh automatically promotes the model's `unique_key`.
- For `INCREMENTAL_BY_TIME_RANGE` and `SCD_TYPE_2_*`, specify `physical_properties (unique_key = (...))`. Include `valid_from` in `unique_key` for SCD Type 2 models so historical versions remain distinct.

## Table Properties (`physical_properties`)

Configure Doris OLAP table clauses in `MODEL (physical_properties (...))`. Key columns are automatically ordered first in `CREATE TABLE` statements as required by Doris.

| Property | Example | Notes |
| ---------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `unique_key` | `unique_key = (user_id, event_date)` | Sets `UNIQUE KEY` and defaults Merge-on-Write + `HASH` auto distribution.|
| `duplicate_key` | `duplicate_key = (user_id, event_date)` | Sets `DUPLICATE KEY` explicitly. |
| `partition_by` | `partition_by = RANGE(event_date)` / `LIST(region)` | `RANGE` or `LIST` partitioning (use `partitions` for initial partitions).|
| `partitions` | `partitions = ('PARTITION p2025 VALUES LESS THAN ("2026-01-01")')` | Initial partition definitions for `RANGE` / `LIST` tables. |
| `distributed_by` | `'HASH(user_id) BUCKETS 8'` / `'HASH(user_id) BUCKETS AUTO'` / `'RANDOM'` | Distribution strategy and bucket count. |
| Generic keys | `replication_num = '1'` | Passed directly into Doris `PROPERTIES (...)` as string pairs. |

### Example: Incremental Model

```sql
MODEL (
name analytics.daily_events,
kind INCREMENTAL_BY_TIME_RANGE (
time_column event_date
),
physical_properties (
unique_key = (user_id, event_date),
distributed_by = 'HASH(user_id) BUCKETS AUTO'
)
);

SELECT
user_id,
event_date,
event_count
FROM raw.events
WHERE event_date BETWEEN @start_ds AND @end_ds;
```

## v1 Scope & Limitations

- **Scalar types only:** Supports Doris scalar types (`BOOLEAN`, `TINYINT`, `SMALLINT`, `INT`, `BIGINT`, `FLOAT`, `DOUBLE`, `DECIMAL`, `CHAR`, `VARCHAR`, `STRING`/`TEXT`, `DATE`, `DATETIME`). Complex types (`STRUCT`, `MAP`, `ARRAY`, `JSON`, `VARIANT`) and `AGGREGATE KEY` tables are not supported in v1.
- **No materialized views or external catalogs in v1:** Targets standard Doris internal tables and regular views (`kind VIEW`).
- **Non-atomic `FULL` replacement:** Doris does not support `CREATE OR REPLACE TABLE` or multi-statement DDL/DML transactions; `FULL` refreshes empty and repopulate the target table using separate statements.
- **No tuple `IN` or standalone `CREATE INDEX`:** Handled automatically via adapter capability flags (`SUPPORTS_TUPLE_IN = False`, `SUPPORTS_INDEXES = False`).
- **Async schema changes:** `alter_table` polls `SHOW ALTER TABLE COLUMN` until each `ALTER TABLE` job completes so sequential alters do not conflict.
1 change: 1 addition & 0 deletions docs/integrations/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ SQLMesh supports the following execution engines for running SQLMesh projects (e
* [ClickHouse](./engines/clickhouse.md) (clickhouse)
* [Databricks](./engines/databricks.md) (databricks)
* [Db2](./engines/db2.md) (db2)
* [Doris](./engines/doris.md) (doris)
* [DuckDB](./engines/duckdb.md) (duckdb)
* [Fabric](./engines/fabric.md) (fabric)
* [MotherDuck](./engines/motherduck.md) (motherduck)
Expand Down
1 change: 1 addition & 0 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ These pages describe the connection configuration options for each execution eng
* [BigQuery](../integrations/engines/bigquery.md)
* [ClickHouse](../integrations/engines/clickhouse.md)
* [Databricks](../integrations/engines/databricks.md)
* [Doris](../integrations/engines/doris.md)
* [DuckDB](../integrations/engines/duckdb.md)
* [Fabric](../integrations/engines/fabric.md)
* [MotherDuck](../integrations/engines/motherduck.md)
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ nav:
- integrations/engines/clickhouse.md
- integrations/engines/databricks.md
- integrations/engines/db2.md
- integrations/engines/doris.md
- integrations/engines/duckdb.md
- integrations/engines/fabric.md
- integrations/engines/motherduck.md
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ db2 = [
"ibm_db",
"db2-sqlglot-dialect>=1.1.0;python_version>=\"3.10\""
]
doris = ["pymysql"]
duckdb = []
fabric = ["pyodbc>=5.0.0"]
fabric-mssql-python = ["mssql-python>=1.1.0;python_version>=\"3.10\""]
Expand Down Expand Up @@ -291,6 +292,7 @@ markers = [
"trino: test for Trino (all connectors)",
"risingwave: test for Risingwave",
"starrocks: test for StarRocks",
"doris: test for Apache Doris",

# Other
"set_default_connection",
Expand Down
1 change: 1 addition & 0 deletions sqlmesh/core/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
BigQueryConnectionConfig as BigQueryConnectionConfig,
ConnectionConfig as ConnectionConfig,
DatabricksConnectionConfig as DatabricksConnectionConfig,
DorisConnectionConfig as DorisConnectionConfig,
DuckDBConnectionConfig as DuckDBConnectionConfig,
FabricConnectionConfig as FabricConnectionConfig,
GCPPostgresConnectionConfig as GCPPostgresConnectionConfig,
Expand Down
74 changes: 74 additions & 0 deletions sqlmesh/core/config/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
# Nullable types are problematic
"clickhouse",
"starrocks",
"doris",
# Db2 rejects table names starting with underscore (_versions, _snapshots,
# _environments, _intervals). Use a separate state_connection (e.g., DuckDB).
"db2",
Expand Down Expand Up @@ -2651,6 +2652,79 @@ def _connection_factory(self) -> t.Callable:
return connect


class DorisConnectionConfig(ConnectionConfig):
"""
Configuration for Apache Doris using MySQL protocol (PyMySQL).

Args:
host: The hostname of the Doris FE node.
user: The username to use for authentication.
password: The password to use for authentication. Default is empty string.
port: The query port number of the Doris FE node. Default is 9030.
database: The optional database name.
charset: The optional character set.
collation: The optional collation.
ssl_disabled: Whether to disable SSL connection.
connect_timeout: Connection timeout in seconds. Default is 10.
concurrent_tasks: The maximum number of tasks that can use this connection concurrently.
register_comments: Whether or not to register model comments with the SQL engine.
local_infile: Whether or not to allow local file access.
pre_ping: Whether or not to pre-ping the connection before starting a new transaction.
"""

host: str
user: str
password: str = ""
port: t.Optional[int] = 9030
database: t.Optional[str] = None
charset: t.Optional[str] = None
collation: t.Optional[str] = None
ssl_disabled: t.Optional[bool] = None
connect_timeout: t.Optional[int] = 10

concurrent_tasks: int = 4
register_comments: bool = True
local_infile: bool = False
pre_ping: bool = True

type_: t.Literal["doris"] = Field(alias="type", default="doris")
DIALECT: t.ClassVar[t.Literal["doris"]] = "doris"
DISPLAY_NAME: t.ClassVar[t.Literal["Apache Doris"]] = "Apache Doris"
DISPLAY_ORDER: t.ClassVar[t.Literal[20]] = 20

_engine_import_validator = _get_engine_import_validator("pymysql", "doris")

@property
def _static_connection_kwargs(self) -> t.Dict[str, t.Any]:
return {"autocommit": True}

@property
def _connection_kwargs_keys(self) -> t.Set[str]:
connection_keys = {"host", "user", "password"}
for field in (
"port",
"database",
"charset",
"collation",
"ssl_disabled",
"connect_timeout",
"local_infile",
):
if getattr(self, field) is not None:
connection_keys.add(field)
return connection_keys

@property
def _engine_adapter(self) -> t.Type[EngineAdapter]:
return engine_adapter.DorisEngineAdapter

@property
def _connection_factory(self) -> t.Callable:
from pymysql import connect

return connect


_CONNECTION_CONFIG_EXCLUDE: t.Set[t.Type[ConnectionConfig]] = {
ConnectionConfig, # type: ignore[type-abstract]
BaseDuckDBConnectionConfig, # type: ignore[type-abstract]
Expand Down
2 changes: 2 additions & 0 deletions sqlmesh/core/engine_adapter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from sqlmesh.core.engine_adapter.bigquery import BigQueryEngineAdapter
from sqlmesh.core.engine_adapter.clickhouse import ClickhouseEngineAdapter
from sqlmesh.core.engine_adapter.databricks import DatabricksEngineAdapter
from sqlmesh.core.engine_adapter.doris import DorisEngineAdapter
from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter
from sqlmesh.core.engine_adapter.mssql import MSSQLEngineAdapter
from sqlmesh.core.engine_adapter.mysql import MySQLEngineAdapter
Expand Down Expand Up @@ -50,6 +51,7 @@
"risingwave": RisingwaveEngineAdapter,
"fabric": FabricEngineAdapter,
"starrocks": StarRocksEngineAdapter,
"doris": DorisEngineAdapter,
}

# Add DB2 to the registry only when the dialect package is present
Expand Down
Loading