From 29c5844fed4f879b906249a3541649a74c8b4027 Mon Sep 17 00:00:00 2001 From: Bruce Arctor <5032356+brucearctor@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:20:08 -0800 Subject: [PATCH 1/2] feat: add Apache Doris engine adapter (v1) --- .github/scripts/wait-for-db.sh | 37 + .github/workflows/pr.yaml | 1 + Makefile | 15 + docs/guides/connections.md | 1 + docs/installation.md | 1 + docs/integrations/engines/doris.md | 127 ++++ docs/integrations/overview.md | 1 + docs/reference/configuration.md | 1 + mkdocs.yml | 1 + pyproject.toml | 2 + sqlmesh/core/config/__init__.py | 1 + sqlmesh/core/config/connection.py | 74 ++ sqlmesh/core/engine_adapter/__init__.py | 2 + sqlmesh/core/engine_adapter/doris.py | 636 ++++++++++++++++++ .../engine_adapter/integration/__init__.py | 11 +- .../engine_adapter/integration/config.yaml | 10 + .../integration/docker/compose.doris.yaml | 49 ++ .../integration/test_integration.py | 26 +- .../integration/test_integration_doris.py | 289 ++++++++ tests/core/engine_adapter/test_doris.py | 353 ++++++++++ tests/core/test_connection_config.py | 58 ++ 21 files changed, 1689 insertions(+), 7 deletions(-) create mode 100644 docs/integrations/engines/doris.md create mode 100644 sqlmesh/core/engine_adapter/doris.py create mode 100644 tests/core/engine_adapter/integration/docker/compose.doris.yaml create mode 100644 tests/core/engine_adapter/integration/test_integration_doris.py create mode 100644 tests/core/engine_adapter/test_doris.py diff --git a/.github/scripts/wait-for-db.sh b/.github/scripts/wait-for-db.sh index 4a076f31f8..07806fcdff 100755 --- a/.github/scripts/wait-for-db.sh +++ b/.github/scripts/wait-for-db.sh @@ -81,6 +81,43 @@ 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() { + probe_port 9030 + + echo "Waiting for Doris FE MySQL endpoint..." + local deadline=$((SECONDS + 180)) + 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' diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 699277a25b..e264dcf49f 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -308,6 +308,7 @@ jobs: clickhouse-datalake, risingwave, starrocks, + doris, ] env: PYTEST_XDIST_AUTO_NUM_WORKERS: 2 diff --git a/Makefile b/Makefile index c25c87106d..653977e17a 100644 --- a/Makefile +++ b/Makefile @@ -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 ${*} @@ -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 # ################# diff --git a/docs/guides/connections.md b/docs/guides/connections.md index 1345905bf7..bf6d4811d6 100644 --- a/docs/guides/connections.md +++ b/docs/guides/connections.md @@ -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) diff --git a/docs/installation.md b/docs/installation.md index 6bcac928e5..221a40fcce 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -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]"` | diff --git a/docs/integrations/engines/doris.md b/docs/integrations/engines/doris.md new file mode 100644 index 0000000000..a718384760 --- /dev/null +++ b/docs/integrations/engines/doris.md @@ -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: ./state/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() 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. diff --git a/docs/integrations/overview.md b/docs/integrations/overview.md index 1c9d56b7e2..6e0398eb5e 100644 --- a/docs/integrations/overview.md +++ b/docs/integrations/overview.md @@ -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) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 84e015e0b6..dcdc65511d 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -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) diff --git a/mkdocs.yml b/mkdocs.yml index 3ff165d009..ff52d87c9a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -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 diff --git a/pyproject.toml b/pyproject.toml index 6eda76bf4d..87315247ff 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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\""] @@ -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", diff --git a/sqlmesh/core/config/__init__.py b/sqlmesh/core/config/__init__.py index 50d2d9a5a2..3113c61435 100644 --- a/sqlmesh/core/config/__init__.py +++ b/sqlmesh/core/config/__init__.py @@ -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, diff --git a/sqlmesh/core/config/connection.py b/sqlmesh/core/config/connection.py index c23c468841..3babb62369 100644 --- a/sqlmesh/core/config/connection.py +++ b/sqlmesh/core/config/connection.py @@ -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", @@ -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] diff --git a/sqlmesh/core/engine_adapter/__init__.py b/sqlmesh/core/engine_adapter/__init__.py index 658b149753..bcb70e87a1 100644 --- a/sqlmesh/core/engine_adapter/__init__.py +++ b/sqlmesh/core/engine_adapter/__init__.py @@ -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 @@ -50,6 +51,7 @@ "risingwave": RisingwaveEngineAdapter, "fabric": FabricEngineAdapter, "starrocks": StarRocksEngineAdapter, + "doris": DorisEngineAdapter, } # Add DB2 to the registry only when the dialect package is present diff --git a/sqlmesh/core/engine_adapter/doris.py b/sqlmesh/core/engine_adapter/doris.py new file mode 100644 index 0000000000..22f38fe4d6 --- /dev/null +++ b/sqlmesh/core/engine_adapter/doris.py @@ -0,0 +1,636 @@ +from __future__ import annotations + +import logging +import re +import time +import typing as t + +from sqlglot import exp, parse_one + +from sqlmesh.core.engine_adapter.base import EngineAdapter +from sqlmesh.core.engine_adapter.mysql import MySQLEngineAdapter +from sqlmesh.core.engine_adapter.shared import ( + CommentCreationView, + set_catalog, +) +from sqlmesh.core.schema_diff import TableAlterOperation +from sqlmesh.utils import columns_to_types_all_known +from sqlmesh.utils.errors import SQLMeshError + +if t.TYPE_CHECKING: + from sqlmesh.core._typing import TableName + from sqlmesh.core.engine_adapter._typing import QueryOrDF + from sqlmesh.core.engine_adapter.shared import SourceQuery + from sqlmesh.core.node import IntervalUnit + +logger = logging.getLogger(__name__) + +_BUCKETS_RE = re.compile(r"^(.+?)(?:\s+BUCKETS\s+(\d+|AUTO))?$", re.IGNORECASE) +_HASH_RE = re.compile(r"^HASH\s*\((.+)\)$", re.IGNORECASE) +_PARTITION_FUNC_RE = re.compile(r"^(RANGE|LIST)\s*\((.+)\)$", re.IGNORECASE) + + +@set_catalog() +class DorisEngineAdapter(MySQLEngineAdapter): + DIALECT = "doris" + DEFAULT_BATCH_SIZE = 10000 + SUPPORTS_TRANSACTIONS = False + SUPPORTS_INDEXES = False + SUPPORTS_TUPLE_IN = False + COMMENT_CREATION_VIEW = CommentCreationView.IN_SCHEMA_DEF_NO_COMMANDS + SCHEMA_DIFFER_KWARGS = { + "parameterized_type_defaults": { + exp.DataType.build("DECIMAL", dialect=DIALECT).this: [(38, 9), (9, 0), (0,)], + exp.DataType.build("CHAR", dialect=DIALECT).this: [(1,)], + exp.DataType.build("VARCHAR", dialect=DIALECT).this: [(65533,)], + exp.DataType.build("DATETIME", dialect=DIALECT).this: [(0,)], + }, + } + + # Override: No capability flag converts unconditional DELETE ... WHERE TRUE + # (emitted by replace_query / SCD_TYPE_2 when SUPPORTS_REPLACE_TABLE = False) to + # TRUNCATE TABLE, and Doris rejects WHERE TRUE deletes on DUPLICATE KEY tables. + def delete_from( + self, + table_name: TableName, + where: t.Optional[t.Union[str, exp.Expr]] = None, + ) -> None: + where_expr = ( + parse_one(where, dialect=self.dialect) if isinstance(where, str) and where else where + ) + if not where_expr or where_expr == exp.true(): + self._truncate_table(table_name) + return + + super().delete_from(table_name, where_expr) + + # Override: MySQLEngineAdapter._replace_by_key uses MySQL's multi-table + # 'DELETE _target FROM ... INNER JOIN' syntax for composite keys, which Doris rejects. + # No capability flag disables that override, so delegate directly to + # EngineAdapter._replace_by_key (CONCAT_WS IN subquery), which Doris supports on + # UNIQUE KEY tables. + def _replace_by_key( + self, + target_table: TableName, + source_table: QueryOrDF, + target_columns_to_types: t.Optional[t.Dict[str, exp.DataType]], + key: t.Sequence[exp.Expr], + is_unique_key: bool, + source_columns: t.Optional[t.List[str]] = None, + ) -> None: + EngineAdapter._replace_by_key( + self, + target_table, + source_table, + target_columns_to_types, + key, + is_unique_key, + source_columns=source_columns, + ) + + # Override: Dedicated EngineAdapter hook (no capability flag) to enforce engine + # table-model requirements for incremental models. Doris rejects subquery DELETE + # statements on DUPLICATE KEY tables, so incremental models require a UNIQUE KEY table. + def adjust_physical_properties_for_incremental( + self, + physical_properties: t.Dict[str, t.Any], + *, + requires_delete_capable_table: bool, + unique_key: t.Optional[t.List[exp.Expr]], + model_name: str, + ) -> t.Dict[str, t.Any]: + if not requires_delete_capable_table or "unique_key" in physical_properties: + return physical_properties + + if unique_key: + physical_properties["unique_key"] = ( + unique_key[0] if len(unique_key) == 1 else exp.Tuple(expressions=unique_key) + ) + logger.info( + "Model '%s' promoted to UNIQUE KEY table on Doris to support DELETE/MERGE operations.", + model_name, + ) + return physical_properties + + raise SQLMeshError( + f"Doris incremental model '{model_name}' requires a UNIQUE KEY table. " + "DUPLICATE KEY tables do not support the subquery DELETE operations used by " + "incremental models. Specify `physical_properties (unique_key = (...))`, or set " + "`unique_key` on INCREMENTAL_BY_UNIQUE_KEY models (for SCD_TYPE_2 models, include " + "`valid_from` in `unique_key` so historical versions are preserved)." + ) + + # Override: Doris requires DUPLICATE KEY / UNIQUE KEY columns to appear as an ordered + # prefix of the CREATE TABLE column list; no capability flag handles column reordering. + def _create_table_from_columns( + self, + table_name: TableName, + target_columns_to_types: t.Dict[str, exp.DataType], + primary_key: t.Optional[t.Tuple[str, ...]] = None, + exists: bool = True, + table_description: t.Optional[str] = None, + column_descriptions: t.Optional[t.Dict[str, str]] = None, + **kwargs: t.Any, + ) -> None: + if primary_key: + raise SQLMeshError( + "Apache Doris does not support PRIMARY KEY tables in SQLMesh v1. " + "Use `unique_key` or `duplicate_key` in `physical_properties` instead." + ) + + table_properties = kwargs.get("table_properties") or {} + key_type, key_cols = self._extract_key_spec(table_properties) + if key_cols: + target_columns_to_types = self._reorder_columns_for_key( + target_columns_to_types, key_cols, key_type or "key" + ) + + super()._create_table_from_columns( + table_name=table_name, + target_columns_to_types=target_columns_to_types, + primary_key=None, + exists=exists, + table_description=table_description, + column_descriptions=column_descriptions, + **kwargs, + ) + + # Override: Doris requires DUPLICATE KEY / UNIQUE KEY columns to appear as an ordered + # prefix in CTAS schemas and SELECT projections; no capability flag handles key reordering. + def _create_table_from_source_queries( + self, + table_name: TableName, + source_queries: t.List[SourceQuery], + target_columns_to_types: t.Optional[t.Dict[str, exp.DataType]] = None, + exists: bool = True, + replace: bool = False, + table_description: t.Optional[str] = None, + column_descriptions: t.Optional[t.Dict[str, str]] = None, + table_kind: t.Optional[str] = None, + track_rows_processed: bool = True, + **kwargs: t.Any, + ) -> None: + table_properties = kwargs.get("table_properties") or {} + key_type, key_cols = self._extract_key_spec(table_properties) + if key_cols: + if target_columns_to_types: + target_columns_to_types = self._reorder_columns_for_key( + target_columns_to_types, key_cols, key_type or "key" + ) + if not ( + target_columns_to_types and columns_to_types_all_known(target_columns_to_types) + ): + resolved_key_type = key_type or "key" + for source_query in source_queries: + source_query.add_transform( + lambda q: self._reorder_query_for_key(q, key_cols, resolved_key_type) + ) + + super()._create_table_from_source_queries( + table_name=table_name, + source_queries=source_queries, + target_columns_to_types=target_columns_to_types, + exists=exists, + replace=replace, + table_description=table_description, + column_descriptions=column_descriptions, + table_kind=table_kind, + track_rows_processed=track_rows_processed, + **kwargs, + ) + + # Override: Base _build_table_properties_exp only handles table comments and + # creatable_type; Doris requires ordered post-schema OLAP clauses (KEY, COMMENT, + # PARTITION BY RANGE/LIST, DISTRIBUTED BY, PROPERTIES) that have no capability flags. + def _build_table_properties_exp( + self, + catalog_name: t.Optional[str] = None, + table_format: t.Optional[str] = None, + storage_format: t.Optional[str] = None, + partitioned_by: t.Optional[t.List[exp.Expr]] = None, + partition_interval_unit: t.Optional[IntervalUnit] = None, + clustered_by: t.Optional[t.List[exp.Expr]] = None, + table_properties: t.Optional[t.Dict[str, exp.Expr]] = None, + target_columns_to_types: t.Optional[t.Dict[str, exp.DataType]] = None, + table_description: t.Optional[str] = None, + table_kind: t.Optional[str] = None, + **kwargs: t.Any, + ) -> t.Optional[exp.Properties]: + props: t.Dict[str, t.Any] = dict(table_properties) if table_properties else {} + properties: t.List[exp.Expr] = [] + + # 1. Table key clause (UNIQUE KEY / DUPLICATE KEY) + key_type, key_cols = self._extract_key_spec(props) + if key_type == "unique_key": + props.pop("unique_key", None) + properties.append( + exp.UniqueKeyProperty(expressions=[exp.to_column(c) for c in key_cols]) + ) + elif key_type == "duplicate_key": + props.pop("duplicate_key", None) + properties.append( + exp.DuplicateKeyProperty(expressions=[exp.to_column(c) for c in key_cols]) + ) + + # 2. Table comment (must precede PARTITION BY / DISTRIBUTED BY / PROPERTIES) + if table_description: + properties.append( + exp.SchemaCommentProperty( + this=exp.Literal.string(self._truncate_table_comment(table_description)) + ) + ) + + # 3. Partition clause (only explicit RANGE(...) / LIST(...); bare partitioned_by columns + # are ignored because Doris requires RANGE/LIST with NOT NULL partition columns) + partition_by = props.pop("partition_by", None) + partitions_raw = props.pop("partitions", None) + partition_spec = None + if partition_by is not None: + partition_spec = self._parse_partition_spec(partition_by) + if partition_spec is None: + raise SQLMeshError( + f"Unsupported Doris `partition_by` value: {partition_by!r}. " + "Expected `RANGE(...)` or `LIST(...)`." + ) + elif partitioned_by and len(partitioned_by) == 1: + partition_spec = self._parse_partition_spec(partitioned_by[0]) + + if partition_spec is not None: + partition_kind, partition_cols = partition_spec + create_expressions = self._parse_partitions(partitions_raw) if partitions_raw else None + if partition_kind == "RANGE": + properties.append( + exp.PartitionByRangeProperty( + partition_expressions=partition_cols, + create_expressions=create_expressions, + ) + ) + else: + properties.append( + exp.PartitionByListProperty( + partition_expressions=partition_cols, + create_expressions=create_expressions, + ) + ) + + # 4. Distribution clause (UNIQUE KEY tables require explicit HASH distribution) + distributed_by = props.pop("distributed_by", None) + if distributed_by is not None: + properties.append(self._parse_distributed_by(distributed_by)) + elif key_type == "unique_key" and key_cols: + properties.append( + exp.DistributedByProperty( + kind=exp.var("HASH"), + expressions=[exp.to_column(c) for c in key_cols], + buckets=exp.var("AUTO"), + ) + ) + + # 5. Generic PROPERTIES (...) + creatable_type = self._pop_creatable_type_from_properties(props) + if creatable_type: + properties.append(creatable_type) + + if key_type == "unique_key" and not any( + k.lower() == "enable_unique_key_merge_on_write" for k in props + ): + props["enable_unique_key_merge_on_write"] = "true" + + for key, value in props.items(): + properties.append( + exp.Property( + this=exp.to_identifier(key), + value=self._to_property_string_literal(value), + ) + ) + + return exp.Properties(expressions=properties) if properties else None + + # Override: MySQLEngineAdapter emits 'ALTER TABLE t COMMENT = ...', which Doris rejects; + # Doris requires 'ALTER TABLE t MODIFY COMMENT ...'. No capability flag controls comment ALTER syntax. + def _build_create_comment_table_exp( + self, table: exp.Table, table_comment: str, table_kind: str = "TABLE" + ) -> str: + table_sql = table.sql(dialect=self.dialect, identify=True) + comment_sql = exp.Literal.string(self._truncate_table_comment(table_comment)).sql( + dialect=self.dialect + ) + return f"ALTER TABLE {table_sql} MODIFY COMMENT {comment_sql}" + + # Override: MySQLEngineAdapter._create_column_comments parses SHOW CREATE TABLE and runs + # 'ALTER TABLE MODIFY col type COMMENT ...', which Doris rejects (missing COLUMN keyword and + # cannot re-specify distribution column types). Delegate to EngineAdapter._create_column_comments + # with Doris's 'ALTER TABLE MODIFY COLUMN col COMMENT ...' syntax. + def _create_column_comments( + self, + table_name: TableName, + column_comments: t.Dict[str, str], + table_kind: str = "TABLE", + materialized_view: bool = False, + table_format: t.Optional[str] = None, + ) -> None: + EngineAdapter._create_column_comments( + self, + table_name, + column_comments, + table_kind=table_kind, + materialized_view=materialized_view, + table_format=table_format, + ) + + # Override: EngineAdapter base generates standard COMMENT ON COLUMN, which Doris rejects; + # Doris requires 'ALTER TABLE t MODIFY COLUMN c COMMENT ...'. No capability flag covers this. + def _build_create_comment_column_exp( + self, + table: exp.Table, + column_name: str, + column_comment: str, + table_kind: str = "TABLE", + ) -> str: + table_sql = table.sql(dialect=self.dialect, identify=True) + column_sql = exp.to_identifier(column_name).sql(dialect=self.dialect, identify=True) + comment_sql = exp.Literal.string(self._truncate_column_comment(column_comment)).sql( + dialect=self.dialect + ) + return f"ALTER TABLE {table_sql} MODIFY COLUMN {column_sql} COMMENT {comment_sql}" + + # Override: Doris runs ALTER TABLE schema changes asynchronously and rejects subsequent + # ALTER or DROP statements while the table is in SCHEMA_CHANGE state. No capability flag + # polls async schema-change completion. + def alter_table( + self, + alter_expressions: t.Union[t.List[exp.Alter], t.List[TableAlterOperation]], + table_format: t.Optional[str] = None, + ) -> None: + for alter_expression in [ + x.expression if isinstance(x, TableAlterOperation) else x for x in alter_expressions + ]: + self.execute(alter_expression) + if isinstance(alter_expression, exp.Alter) and isinstance( + alter_expression.this, exp.Table + ): + self._wait_for_schema_change(alter_expression.this) + + def _wait_for_schema_change( + self, + table: exp.Table, + timeout_seconds: float = 60.0, + poll_interval: float = 0.25, + ) -> None: + db_clause = ( + f" FROM {exp.to_identifier(table.db).sql(dialect=self.dialect, identify=True)}" + if table.db + else "" + ) + table_literal = exp.Literal.string(table.name).sql(dialect=self.dialect) + status_sql = ( + f"SHOW ALTER TABLE COLUMN{db_clause} " + f"WHERE TableName = {table_literal} ORDER BY CreateTime DESC LIMIT 1" + ) + deadline = time.monotonic() + timeout_seconds + + while True: + self.execute(status_sql) + row = self.cursor.fetchone() + if not row: + return + + columns = [d[0].lower() for d in (self.cursor.description or []) if d] + if "state" in columns: + state_idx = columns.index("state") + msg_idx = columns.index("msg") if "msg" in columns else None + elif len(row) > 9: + state_idx = 9 + msg_idx = 10 if len(row) > 10 else None + else: + return + + state = str(row[state_idx]).upper() + if state == "FINISHED": + return + if state == "CANCELLED": + msg = row[msg_idx] if msg_idx is not None else "" + raise SQLMeshError( + f"Doris schema change on table '{table.sql(dialect=self.dialect)}' was cancelled: {msg}" + ) + if time.monotonic() >= deadline: + raise SQLMeshError( + f"Timed out waiting for Doris schema change on table '{table.sql(dialect=self.dialect)}' " + f"(last state: {state})." + ) + time.sleep(poll_interval) + + def _extract_key_spec( + self, table_properties: t.Mapping[str, t.Any] + ) -> t.Tuple[t.Optional[str], t.List[str]]: + if "primary_key" in table_properties: + raise SQLMeshError( + "Apache Doris does not support PRIMARY KEY tables in SQLMesh v1. " + "Use `unique_key` or `duplicate_key` in `physical_properties` instead." + ) + if "aggregate_key" in table_properties: + raise SQLMeshError( + "Apache Doris AGGREGATE KEY tables are not supported in SQLMesh v1. " + "Use `unique_key` or `duplicate_key` in `physical_properties` instead." + ) + + has_unique = "unique_key" in table_properties + has_duplicate = "duplicate_key" in table_properties + if has_unique and has_duplicate: + raise SQLMeshError( + "Cannot specify both `unique_key` and `duplicate_key` on a Doris table." + ) + + if has_unique: + return "unique_key", self._parse_column_list( + table_properties["unique_key"], "unique_key" + ) + if has_duplicate: + return "duplicate_key", self._parse_column_list( + table_properties["duplicate_key"], "duplicate_key" + ) + return None, [] + + def _reorder_columns_for_key( + self, + target_columns_to_types: t.Dict[str, exp.DataType], + key_columns: t.Sequence[str], + key_type: str, + ) -> t.Dict[str, exp.DataType]: + missing = [c for c in key_columns if c not in target_columns_to_types] + if missing: + raise SQLMeshError( + f"{key_type} columns {missing} not found in table columns {list(target_columns_to_types)}." + ) + + key_set = set(key_columns) + reordered = {col: target_columns_to_types[col] for col in key_columns} + for col, dtype in target_columns_to_types.items(): + if col not in key_set: + reordered[col] = dtype + return reordered + + @staticmethod + def _reorder_query_for_key( + query: exp.Expr, + key_columns: t.Sequence[str], + key_type: str, + ) -> exp.Query: + if not isinstance(query, exp.Query) or query.parent is not None: + return t.cast(exp.Query, query) + + selects = [col for col in query.named_selects if col != "*"] + if not selects or selects[: len(key_columns)] == list(key_columns): + return query + + missing = [c for c in key_columns if c not in selects] + if missing: + raise SQLMeshError( + f"{key_type} columns {missing} not found in query output columns {selects}." + ) + + key_set = set(key_columns) + ordered_cols = list(key_columns) + [c for c in selects if c not in key_set] + query = query.copy() + with_ = query.args.pop("with_", None) + wrapped = exp.select(*[exp.column(c, quoted=True) for c in ordered_cols]).from_( + query.subquery("_subquery", copy=False), copy=False + ) + if with_: + wrapped.set("with_", with_) + return wrapped + + def _parse_column_list(self, value: t.Any, prop_name: str) -> t.List[str]: + while isinstance(value, exp.Paren): + value = value.this + if isinstance(value, (exp.Tuple, exp.Array)): + items: t.List[t.Any] = list(value.expressions) + elif isinstance(value, (list, tuple)): + items = list(value) + elif isinstance(value, exp.Literal) and value.is_string: + items = self._split_csv_string(value.this) + elif isinstance(value, str): + items = self._split_csv_string(value) + else: + items = [] if value is None else [value] + + cols = [self._extract_identifier_name(item, prop_name) for item in items] + if not cols: + raise SQLMeshError(f"Doris `{prop_name}` must specify at least one column.") + return cols + + @staticmethod + def _split_csv_string(text: str) -> t.List[str]: + stripped = text.strip() + if stripped.startswith("(") and stripped.endswith(")"): + stripped = stripped[1:-1].strip() + return [part.strip() for part in stripped.split(",") if part.strip()] + + @staticmethod + def _extract_identifier_name(item: t.Any, prop_name: str) -> str: + if isinstance(item, (exp.Column, exp.Identifier, exp.Var)): + return item.name + if isinstance(item, exp.Literal) and item.is_string: + return item.this.strip().strip('`"') + if isinstance(item, str): + return item.strip().strip('`"') + raise SQLMeshError(f"Invalid column reference {item!r} in Doris `{prop_name}`.") + + def _parse_partition_spec(self, expr: t.Any) -> t.Optional[t.Tuple[str, t.List[exp.Expr]]]: + while isinstance(expr, exp.Paren): + expr = expr.this + if isinstance(expr, exp.Tuple) and len(expr.expressions) == 1: + expr = expr.expressions[0] + if isinstance(expr, exp.Literal) and expr.is_string: + expr = expr.this + if isinstance(expr, str): + match = _PARTITION_FUNC_RE.match(expr.strip()) + if not match: + return None + str_cols: t.List[exp.Expr] = [ + exp.to_column(c) for c in self._split_csv_string(match.group(2)) + ] + return (str(match.group(1)).upper(), str_cols) if str_cols else None + if isinstance(expr, exp.List) or ( + isinstance(expr, exp.Anonymous) and str(expr.this).upper() in ("RANGE", "LIST") + ): + kind = "LIST" if isinstance(expr, exp.List) else str(expr.this).upper() + ast_cols: t.List[exp.Expr] = [ + col if isinstance(col, exp.Column) else exp.to_column(col.name) + for col in expr.expressions + ] + return (kind, ast_cols) if ast_cols else None + return None + + def _parse_partitions(self, value: t.Any) -> t.List[exp.Var]: + while isinstance(value, exp.Paren): + value = value.this + if isinstance(value, (exp.Tuple, exp.Array)): + items: t.List[t.Any] = list(value.expressions) + elif isinstance(value, (list, tuple)): + items = list(value) + else: + items = [value] + return [ + exp.Var(this=text.strip(), quoted=False) + for item in items + if (text := item.this if isinstance(item, exp.Literal) else str(item)).strip() + ] + + def _parse_distributed_by(self, value: t.Any) -> exp.DistributedByProperty: + while isinstance(value, exp.Paren): + value = value.this + if isinstance(value, exp.Literal) and value.is_string: + text = value.this.strip() + elif isinstance(value, (exp.Var, exp.Identifier, exp.Column)): + text = value.name.strip() + elif isinstance(value, str): + text = value.strip() + else: + raise SQLMeshError(f"Unsupported Doris `distributed_by` value: {value!r}.") + + match = _BUCKETS_RE.match(text) + body = match.group(1).strip() if match else "" + buckets_str = match.group(2) if match else None + if buckets_str is None: + buckets_expr: t.Optional[exp.Expr] = None + elif buckets_str.upper() == "AUTO": + buckets_expr = exp.var("AUTO") + elif buckets_str.isdigit(): + buckets_expr = exp.Literal.number(int(buckets_str)) + else: + raise SQLMeshError( + f"Invalid Doris `buckets` value {buckets_str!r}; expected an integer or AUTO." + ) + + if body.upper() == "RANDOM": + return exp.DistributedByProperty( + kind=exp.var("RANDOM"), expressions=[], buckets=buckets_expr + ) + + hash_match = _HASH_RE.match(body) + if not hash_match: + raise SQLMeshError( + f"Unsupported Doris `distributed_by` clause: {text!r}. Expected `RANDOM` or `HASH(...) [BUCKETS ...]`." + ) + cols = [ + exp.to_column(self._extract_identifier_name(c, "distributed_by")) + for c in self._split_csv_string(hash_match.group(1)) + ] + if not cols: + raise SQLMeshError("Doris HASH distribution requires at least one column.") + return exp.DistributedByProperty( + kind=exp.var("HASH"), expressions=cols, buckets=buckets_expr + ) + + @staticmethod + def _to_property_string_literal(value: t.Any) -> exp.Literal: + if isinstance(value, exp.Literal): + return exp.Literal.string(str(value.this)) + if isinstance(value, exp.Boolean): + return exp.Literal.string("true" if value.this else "false") + if isinstance(value, (exp.Identifier, exp.Var, exp.Column)): + return exp.Literal.string(value.name) + if isinstance(value, bool): + return exp.Literal.string("true" if value else "false") + return exp.Literal.string(str(value)) diff --git a/tests/core/engine_adapter/integration/__init__.py b/tests/core/engine_adapter/integration/__init__.py index fe1951add6..9099e7d876 100644 --- a/tests/core/engine_adapter/integration/__init__.py +++ b/tests/core/engine_adapter/integration/__init__.py @@ -80,6 +80,7 @@ def pytest_marks(self) -> t.List[MarkDecorator]: IntegrationTestEngine("clickhouse", catalog_types=["standalone", "cluster"]), IntegrationTestEngine("risingwave"), IntegrationTestEngine("starrocks"), + IntegrationTestEngine("doris"), # Cloud engines that need paid accounts / special credentials IntegrationTestEngine("clickhouse_cloud", cloud=True), IntegrationTestEngine("redshift", cloud=True), @@ -275,7 +276,7 @@ def timestamp_columns(self) -> t.List[str]: for k, v in self.columns_to_types.items() if v.sql().lower().startswith("timestamp") or (v.sql().lower() == "datetime" and self.dialect == "bigquery") - or (v.sql().lower() == "datetime" and self.dialect == "starrocks") + or (v.sql().lower() == "datetime" and self.dialect in ("starrocks", "doris")) ] @property @@ -318,7 +319,7 @@ def supports_merge(self) -> bool: if self.dialect == "risingwave": return False - if self.dialect == "starrocks": + if self.dialect in ("starrocks", "doris"): return False return True @@ -462,7 +463,7 @@ def get_table_comment( AND pgc.relkind = '{"v" if table_kind == "VIEW" else "r"}' ; """ - elif self.dialect in ["mysql", "snowflake", "starrocks"]: + elif self.dialect in ["mysql", "snowflake", "starrocks", "doris"]: # Snowflake treats all identifiers as uppercase unless they are lowercase and quoted. # They are lowercase and quoted in sushi but not in the inline tests. if self.dialect == "snowflake" and snowflake_capitalize_ids: @@ -473,6 +474,7 @@ def get_table_comment( "mysql": "table_comment", "snowflake": "comment", "starrocks": "table_comment", + "doris": "table_comment", } query = f""" @@ -594,7 +596,7 @@ def get_column_comments( AND pgc.relkind = '{"v" if table_kind == "VIEW" else "r"}' ; """ - elif self.dialect in ["mysql", "snowflake", "trino", "starrocks"]: + elif self.dialect in ["mysql", "snowflake", "trino", "starrocks", "doris"]: # Snowflake treats all identifiers as uppercase unless they are lowercase and quoted. # They are lowercase and quoted in sushi but not in the inline tests. if self.dialect == "snowflake" and snowflake_capitalize_ids: @@ -606,6 +608,7 @@ def get_column_comments( "snowflake": "comment", "trino": "comment", "starrocks": "column_comment", + "doris": "column_comment", } query = f""" diff --git a/tests/core/engine_adapter/integration/config.yaml b/tests/core/engine_adapter/integration/config.yaml index 24ba2b2a6d..931f5e0343 100644 --- a/tests/core/engine_adapter/integration/config.yaml +++ b/tests/core/engine_adapter/integration/config.yaml @@ -128,6 +128,16 @@ gateways: check_import: false state_connection: type: duckdb + inttest_doris: + connection: + type: doris + host: {{ env_var('DOCKER_HOSTNAME', 'localhost') }} + port: 9030 + user: root + password: "" + check_import: false + state_connection: + type: duckdb # Cloud databases diff --git a/tests/core/engine_adapter/integration/docker/compose.doris.yaml b/tests/core/engine_adapter/integration/docker/compose.doris.yaml new file mode 100644 index 0000000000..5d8959fa1e --- /dev/null +++ b/tests/core/engine_adapter/integration/docker/compose.doris.yaml @@ -0,0 +1,49 @@ +services: + doris-fe: + image: apache/doris:fe-4.1.5 + container_name: doris-fe + hostname: doris-fe + entrypoint: ["/bin/bash", "-c"] + command: + - | + sed -i -E 's/-Xmx[0-9]+[mg]/-Xmx2048m/g; s/-Xms[0-9]+[mg]/-Xms512m/g' /opt/apache-doris/fe/conf/fe.conf + echo "priority_networks = 172.30.80.0/24" >> /opt/apache-doris/fe/conf/fe.conf + echo "force_olap_table_replication_num = 1" >> /opt/apache-doris/fe/conf/fe.conf + exec bash /opt/apache-doris/fe/bin/start_fe.sh --console + ports: + - "8030:8030" + - "9030:9030" + networks: + doris_net: + ipv4_address: 172.30.80.2 + + doris-be: + image: apache/doris:be-4.1.5 + container_name: doris-be + hostname: doris-be + depends_on: + - doris-fe + entrypoint: ["/bin/bash", "-c"] + command: + - | + export SKIP_CHECK_ULIMIT=true + ulimit -n 65535 || true + sed -i -E 's/-Xmx[0-9]+[mg]/-Xmx1024m/g' /opt/apache-doris/be/conf/be.conf + echo "priority_networks = 172.30.80.0/24" >> /opt/apache-doris/be/conf/be.conf + echo "mem_limit = 80%" >> /opt/apache-doris/be/conf/be.conf + echo "disable_memory_gc = false" >> /opt/apache-doris/be/conf/be.conf + echo "storage_flood_stage_usage_percent = 99" >> /opt/apache-doris/be/conf/be.conf + echo "storage_flood_stage_left_capacity_bytes = 104857600" >> /opt/apache-doris/be/conf/be.conf + exec bash /opt/apache-doris/be/bin/start_be.sh --console + ports: + - "8040:8040" + - "9050:9050" + networks: + doris_net: + ipv4_address: 172.30.80.3 + +networks: + doris_net: + ipam: + config: + - subnet: 172.30.80.0/24 diff --git a/tests/core/engine_adapter/integration/test_integration.py b/tests/core/engine_adapter/integration/test_integration.py index e3eee97c8b..296cc9d777 100644 --- a/tests/core/engine_adapter/integration/test_integration.py +++ b/tests/core/engine_adapter/integration/test_integration.py @@ -2025,6 +2025,12 @@ def test_sushi( "example uses cross-engine incremental/SCD models without a StarRocks primary_key, so " "this end-to-end test does not apply to StarRocks" ) + if ctx.dialect == "doris": + pytest.skip( + "Doris requires incremental models to use a UNIQUE KEY table; the shared sushi " + "example uses cross-engine incremental models without a Doris unique_key, so this " + "end-to-end test does not apply to Doris" + ) if ctx.dialect == "db2": pytest.skip( "Db2 does not support CREATE SCHEMA IF NOT EXISTS (SQL0104N). The test_sushi " @@ -2439,6 +2445,12 @@ def test_init_project(ctx: TestContext, tmp_path: pathlib.Path): "project's incremental_model has no StarRocks primary_key, so this cross-engine test " "does not apply to StarRocks" ) + if ctx.dialect == "doris": + pytest.skip( + "Doris requires incremental models to use a UNIQUE KEY table; the default example " + "project's incremental_model has no Doris unique_key, so this cross-engine test " + "does not apply to Doris" + ) schema_name = ctx.add_test_suffix(TEST_SCHEMA) state_schema = ctx.add_test_suffix("sqlmesh_state") @@ -2684,6 +2696,7 @@ def test_dialects(ctx: TestContext): "spark": pd.Timestamp("2020-01-01 00:00:00"), "databricks": pd.Timestamp("2020-01-01 00:00:00"), "starrocks": pd.Timestamp("2020-01-01 00:00:00"), + "doris": pd.Timestamp("2020-01-01 00:00:00"), }, ), ( @@ -3248,6 +3261,8 @@ def test_value_normalization( pytest.skip("Trino on Hive doesn't support TIMESTAMP WITH TIME ZONE fields") if ctx.dialect == "fabric": pytest.skip("Fabric doesn't support TIMESTAMP WITH TIME ZONE fields") + if ctx.dialect == "doris": + pytest.skip("Doris v1 maps TIMESTAMPTZ to naive DATETIME on sqlglot 30.8") if not isinstance(ctx.engine_adapter, RowDiffMixin): pytest.skip( @@ -3258,7 +3273,7 @@ def test_value_normalization( # resolve dialect-specific types if column_type in (DATA_TYPE.DATETIME, DATA_TYPE.TIMESTAMP, DATA_TYPE.TIMESTAMPTZ): - if ctx.dialect in ("mysql", "trino"): + if ctx.dialect in ("mysql", "trino", "doris"): # MySQL needs DATETIME(6) instead of DATETIME or subseconds will be truncated. # It also needs TIMESTAMP(6) as the column type for CREATE TABLE or the truncation will occur full_column_type = exp.DataType.build( @@ -3283,8 +3298,7 @@ def test_value_normalization( exp.to_table(ctx.table("test_value_normalization")), dialect=ctx.dialect ) columns_to_types_normalized = { - normalize_identifiers(k, dialect=ctx.dialect).sql(dialect=ctx.dialect): v - for k, v in columns_to_types.items() + normalize_identifiers(k, dialect=ctx.dialect).name: v for k, v in columns_to_types.items() } ctx.engine_adapter.create_table( @@ -3801,6 +3815,12 @@ def test_janitor( "used here has an incremental_model without a StarRocks primary_key, so this " "cross-engine test does not apply to StarRocks" ) + if ctx.dialect == "doris": + pytest.skip( + "Doris requires incremental models to use a UNIQUE KEY table; the example project " + "used here has an incremental_model without a Doris unique_key, so this " + "cross-engine test does not apply to Doris" + ) schema = ctx.schema() # catalog.schema parsed_schema = d.to_schema(schema) diff --git a/tests/core/engine_adapter/integration/test_integration_doris.py b/tests/core/engine_adapter/integration/test_integration_doris.py new file mode 100644 index 0000000000..cdc0754b3c --- /dev/null +++ b/tests/core/engine_adapter/integration/test_integration_doris.py @@ -0,0 +1,289 @@ +"""Live integration tests for the Apache Doris v1 engine adapter.""" + +from __future__ import annotations + +import os +import typing as t +from functools import partial + +import pandas as pd # noqa: TID253 +import pytest +from sqlglot import exp, parse_one + +import sqlmesh.core.dialect as d +from sqlmesh.core.config import Config, GatewayConfig +from sqlmesh.core.config.connection import DorisConnectionConfig, DuckDBConnectionConfig +from sqlmesh.core.context import Context +from sqlmesh.core.engine_adapter.doris import DorisEngineAdapter +from sqlmesh.core.model.definition import load_sql_based_model +from sqlmesh.core.schema_diff import TableAlterOperation +from sqlmesh.utils.errors import SQLMeshError +from tests.core.engine_adapter.integration import TestContext +from tests.utils.pandas import compare_dataframes + +pytestmark = [pytest.mark.doris, pytest.mark.docker, pytest.mark.engine] + + +@pytest.fixture(scope="module") +def doris_connection_config() -> t.Dict[str, t.Any]: + return { + "host": os.getenv("DOCKER_HOSTNAME", "localhost"), + "port": int(os.getenv("DORIS_PORT", "9030")), + "user": os.getenv("DORIS_USER", "root"), + "password": os.getenv("DORIS_PASSWORD", ""), + "autocommit": True, + } + + +@pytest.fixture +def ctx(tmp_path, doris_connection_config) -> t.Generator[TestContext, None, None]: + from pymysql import connect + + adapter = DorisEngineAdapter(partial(connect, **doris_connection_config)) + context = TestContext( + "query", adapter, mark="doris", gateway="manual_doris", tmp_path=tmp_path, is_remote=False + ) + context.init() + try: + yield context + finally: + context.cleanup() + + +def _create_sqlmesh_context(ctx: TestContext, tmp_path) -> Context: + def _mutator(gateway: str, config: Config) -> None: + config.gateways[gateway] = GatewayConfig( + connection=DorisConnectionConfig( + host=os.getenv("DOCKER_HOSTNAME", "localhost"), + port=int(os.getenv("DORIS_PORT", "9030")), + user=os.getenv("DORIS_USER", "root"), + password=os.getenv("DORIS_PASSWORD", ""), + concurrent_tasks=1, + ), + state_connection=DuckDBConnectionConfig(), + ) + config.model_defaults.dialect = "doris" + + return ctx.create_context(path=tmp_path, config_mutator=_mutator) + + +def test_table_types_partitions_and_properties(ctx: TestContext): + adapter = ctx.engine_adapter + + dup_tbl = ctx.table("dup_events") + adapter.create_table( + dup_tbl, + { + "payload": exp.DataType.build("VARCHAR(100)"), + "ds": exp.DataType.build("DATE"), + "id": exp.DataType.build("INT"), + }, + table_properties={ + "duplicate_key": parse_one("(id, ds)"), + "partition_by": parse_one("RANGE(ds)"), + "partitions": parse_one("('PARTITION p2025 VALUES LESS THAN (\"2026-01-01\")')"), + "distributed_by": exp.Literal.string("HASH(id) BUCKETS 2"), + "replication_num": exp.Literal.string("1"), + }, + ) + + uniq_tbl = ctx.table("uniq_orders") + adapter.create_table( + uniq_tbl, + { + "amount": exp.DataType.build("DECIMAL(10, 2)"), + "region": exp.DataType.build("VARCHAR(20)"), + "order_id": exp.DataType.build("BIGINT"), + }, + table_properties={ + "unique_key": parse_one("(order_id, region)"), + "partition_by": parse_one("LIST(region)"), + "partitions": parse_one( + "('PARTITION p_us VALUES IN (\"us\")', 'PARTITION p_eu VALUES IN (\"eu\")')" + ), + "replication_num": exp.Literal.string("1"), + }, + ) + + assert list(adapter.columns(dup_tbl)) == ["id", "ds", "payload"] + assert list(adapter.columns(uniq_tbl)) == ["order_id", "region", "amount"] + + uniq_ddl = adapter.fetchone(f"SHOW CREATE TABLE {uniq_tbl.sql(dialect='doris', identify=True)}") + assert uniq_ddl is not None + assert "UNIQUE KEY(`order_id`, `region`)" in uniq_ddl[1] + assert "PARTITION BY LIST (`region`)" in uniq_ddl[1] + + +def test_composite_key_merge(ctx: TestContext): + adapter = ctx.engine_adapter + comp_tbl = ctx.table("merge_composite") + cols_comp = { + "id": exp.DataType.build("INT"), + "tenant": exp.DataType.build("VARCHAR(20)"), + "val": exp.DataType.build("INT"), + } + adapter.create_table( + comp_tbl, cols_comp, table_properties={"unique_key": parse_one("(id, tenant)")} + ) + adapter.merge( + comp_tbl, + pd.DataFrame([{"id": 1, "tenant": "t1", "val": 10}, {"id": 1, "tenant": "t2", "val": 20}]), + target_columns_to_types=cols_comp, + unique_key=[exp.column("id"), exp.column("tenant")], + ) + adapter.merge( + comp_tbl, + pd.DataFrame([{"id": 1, "tenant": "t2", "val": 99}, {"id": 2, "tenant": "t1", "val": 30}]), + target_columns_to_types=cols_comp, + unique_key=[exp.column("id"), exp.column("tenant")], + ) + ctx.compare_with_current( + comp_tbl, + pd.DataFrame( + [ + {"id": 1, "tenant": "t1", "val": 10}, + {"id": 1, "tenant": "t2", "val": 99}, + {"id": 2, "tenant": "t1", "val": 30}, + ] + ), + ) + + +def test_sequential_alter_table_and_comments(ctx: TestContext): + adapter = ctx.engine_adapter + tbl = ctx.table("alter_and_cmt") + adapter.create_table( + tbl, + {"id": exp.DataType.build("INT"), "name": exp.DataType.build("VARCHAR(20)")}, + table_description="initial table comment", + column_descriptions={"name": "initial col comment"}, + ) + adapter._create_table_comment(tbl, "updated table comment") + adapter._create_column_comments(tbl, {"name": "updated col comment"}) + + assert ctx.get_table_comment(tbl.db, tbl.name) == "updated table comment" + assert ctx.get_column_comments(tbl.db, tbl.name).get("name") == "updated col comment" + + initial_cols = adapter.columns(tbl) + with_extra = {**initial_cols, "extra": exp.DataType.build("INT")} + widened_with_extra = { + "id": initial_cols["id"], + "name": exp.DataType.build("VARCHAR(100)"), + "extra": exp.DataType.build("INT"), + } + widened = {"id": initial_cols["id"], "name": exp.DataType.build("VARCHAR(100)")} + + for target in (with_extra, widened_with_extra, widened): + ops: t.List[TableAlterOperation] = list( + adapter.schema_differ.compare_columns(tbl, adapter.columns(tbl), target) + ) + adapter.alter_table(ops) + cols = adapter.columns(tbl) + assert list(cols) == ["id", "name"] + assert cols["name"].sql(dialect="doris") == "VARCHAR(100)" + + view = ctx.table("cmt_view") + adapter.create_view( + view, + exp.select("id", "name").from_(tbl), + target_columns_to_types={ + "id": exp.DataType.build("INT"), + "name": exp.DataType.build("VARCHAR(100)"), + }, + table_description="view table comment", + column_descriptions={"id": "view id comment"}, + ) + assert ctx.get_table_comment(view.db, view.name, table_kind="VIEW") == "view table comment" + assert ( + ctx.get_column_comments(view.db, view.name, table_kind="VIEW").get("id") + == "view id comment" + ) + + +def test_context_models_end_to_end(ctx: TestContext, tmp_path): + src = ctx.table("raw_src") + schema = src.db + ctx.engine_adapter.create_table( + src, + { + "id": exp.DataType.build("INT"), + "name": exp.DataType.build("VARCHAR(50)"), + "ds": exp.DataType.build("DATE"), + "updated_at": exp.DataType.build("DATETIME"), + }, + table_properties={"unique_key": parse_one("id")}, + ) + src_sql = src.sql(dialect="doris", identify=True) + ctx.engine_adapter.execute( + f"INSERT INTO {src_sql} (id, name, ds, updated_at) VALUES " + "(1, 'alice', '2024-01-01', '2024-01-01 00:00:00'), " + "(2, 'bob', '2024-01-02', '2024-01-02 00:00:00')" + ) + + sqlmesh = _create_sqlmesh_context(ctx, tmp_path) + model_defs = [ + f"MODEL (name {schema}.full_m, kind FULL, dialect doris, start '2024-01-01'); SELECT id, name, ds FROM {src_sql};", + f"MODEL (name {schema}.view_m, kind VIEW, dialect doris, start '2024-01-01', description 'Summary view', columns (id INT, name VARCHAR(50)), column_descriptions (id = 'User ID')); SELECT id, name FROM {schema}.full_m;", + f"MODEL (name {schema}.inc_uk_m, kind INCREMENTAL_BY_UNIQUE_KEY (unique_key id), dialect doris, start '2024-01-01'); SELECT id, name, ds FROM {src_sql} WHERE ds BETWEEN @start_ds AND @end_ds;", + f"MODEL (name {schema}.inc_tr_m, kind INCREMENTAL_BY_TIME_RANGE (time_column ds), dialect doris, start '2024-01-01', physical_properties (unique_key = (id, ds))); SELECT id, name, ds FROM {src_sql} WHERE ds BETWEEN @start_ds AND @end_ds;", + f"MODEL (name {schema}.scd_time_m, kind SCD_TYPE_2_BY_TIME (unique_key id, updated_at_name updated_at), dialect doris, start '2024-01-01', physical_properties (unique_key = (id, valid_from))); SELECT id, name, updated_at FROM {src_sql};", + f"MODEL (name {schema}.scd_col_m, kind SCD_TYPE_2_BY_COLUMN (unique_key id, columns (name)), dialect doris, start '2024-01-01', physical_properties (unique_key = (id, valid_from))); SELECT id, name FROM {src_sql};", + ] + for definition in model_defs: + sqlmesh.upsert_model(load_sql_based_model(d.parse(definition))) + + sqlmesh.plan(execution_time="2024-01-03 00:00:00", auto_apply=True, no_prompts=True) + + for tbl_name in ("full_m", "view_m", "inc_uk_m", "inc_tr_m", "scd_time_m", "scd_col_m"): + row = ctx.engine_adapter.fetchone(f"SELECT COUNT(*) FROM `{schema}`.`{tbl_name}`") + assert row is not None and row[0] == 2 + + assert ctx.get_table_comment(schema, "view_m", table_kind="VIEW") == "Summary view" + physical_schema = f"sqlmesh__{schema}" + physical_view_name = next( + v for v in ctx.get_metadata_results(physical_schema).views if "view_m" in v + ) + assert ( + ctx.get_column_comments(physical_schema, physical_view_name, table_kind="VIEW").get("id") + == "User ID" + ) + + ctx.engine_adapter.execute(f"DELETE FROM {src_sql} WHERE id = 1") + ctx.engine_adapter.execute( + f"INSERT INTO {src_sql} (id, name, ds, updated_at) VALUES " + "(2, 'bob_v2', '2024-01-03', '2024-01-03 00:00:00'), " + "(3, 'carol', '2024-01-03', '2024-01-03 00:00:00')" + ) + sqlmesh.run(execution_time="2024-01-04 00:00:00") + + compare_dataframes( + ctx.engine_adapter.fetchdf(f"SELECT id, name FROM `{schema}`.`inc_uk_m` ORDER BY id"), + pd.DataFrame( + [{"id": 1, "name": "alice"}, {"id": 2, "name": "bob_v2"}, {"id": 3, "name": "carol"}] + ), + ) + compare_dataframes( + ctx.engine_adapter.fetchdf(f"SELECT id, name FROM `{schema}`.`inc_tr_m` ORDER BY id, ds"), + pd.DataFrame( + [ + {"id": 1, "name": "alice"}, + {"id": 2, "name": "bob"}, + {"id": 2, "name": "bob_v2"}, + {"id": 3, "name": "carol"}, + ] + ), + ) + expected_scd = [(1, "alice", 1), (2, "bob", 0), (2, "bob_v2", 1), (3, "carol", 1)] + for scd_tbl in ("scd_time_m", "scd_col_m"): + rows = ctx.engine_adapter.fetchall( + f"SELECT id, name, valid_to IS NULL AS is_current FROM `{schema}`.`{scd_tbl}` ORDER BY id, valid_from" + ) + assert list(rows) == expected_scd + + with pytest.raises(SQLMeshError, match="requires a UNIQUE KEY table"): + ctx.engine_adapter.adjust_physical_properties_for_incremental( + {}, + requires_delete_capable_table=True, + unique_key=None, + model_name=f"{schema}.bad_inc_tr", + ) diff --git a/tests/core/engine_adapter/test_doris.py b/tests/core/engine_adapter/test_doris.py new file mode 100644 index 0000000000..341a9e6733 --- /dev/null +++ b/tests/core/engine_adapter/test_doris.py @@ -0,0 +1,353 @@ +# type: ignore +import typing as t +from unittest.mock import call + +import pytest +from pytest_mock.plugin import MockerFixture +from sqlglot import exp, parse_one + +from sqlmesh.core.engine_adapter import DorisEngineAdapter +from sqlmesh.core.engine_adapter.shared import CommentCreationTable, CommentCreationView +from sqlmesh.utils.errors import SQLMeshError +from tests.core.engine_adapter import to_sql_calls + +pytestmark = [pytest.mark.doris, pytest.mark.engine] + + +def test_capability_flags(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + assert adapter.DIALECT == "doris" + assert adapter.SUPPORTS_TRANSACTIONS is False + assert adapter.SUPPORTS_INDEXES is False + assert adapter.SUPPORTS_TUPLE_IN is False + assert adapter.SUPPORTS_REPLACE_TABLE is False + assert adapter.SUPPORTS_MATERIALIZED_VIEWS is False + assert adapter.COMMENT_CREATION_TABLE == CommentCreationTable.IN_SCHEMA_DEF_NO_CTAS + assert adapter.COMMENT_CREATION_VIEW == CommentCreationView.IN_SCHEMA_DEF_NO_COMMANDS + assert exp.DType.VARCHAR in adapter.SCHEMA_DIFFER_KWARGS["parameterized_type_defaults"] + + +def test_create_table_key_models_and_column_reordering(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + + adapter.create_table( + "db.events", + { + "payload": exp.DataType.build("VARCHAR(100)"), + "ds": exp.DataType.build("DATE"), + "id": exp.DataType.build("BIGINT"), + }, + table_properties={ + "duplicate_key": parse_one("(id, ds)"), + "distributed_by": exp.Var(this="RANDOM"), + }, + ) + + adapter.create_table( + "db.metrics", + { + "val": exp.DataType.build("INT"), + "ds": exp.DataType.build("DATE"), + "id": exp.DataType.build("BIGINT"), + }, + table_properties={ + "unique_key": parse_one("(id, ds)"), + "replication_num": exp.Literal.number(1), + }, + ) + + adapter.create_table( + "db.custom_unique", + {"id": exp.DataType.build("INT"), "val": exp.DataType.build("INT")}, + table_properties={ + "unique_key": parse_one("id"), + "distributed_by": exp.Literal.string("HASH(id) BUCKETS 4"), + "enable_unique_key_merge_on_write": exp.Literal.string("false"), + }, + ) + + assert to_sql_calls(adapter) == [ + "CREATE TABLE IF NOT EXISTS `db`.`events` (`id` BIGINT, `ds` DATE, `payload` VARCHAR(100)) DUPLICATE KEY (`id`, `ds`) DISTRIBUTED BY RANDOM", + "CREATE TABLE IF NOT EXISTS `db`.`metrics` (`id` BIGINT, `ds` DATE, `val` INT) UNIQUE KEY (`id`, `ds`) DISTRIBUTED BY HASH (`id`, `ds`) BUCKETS AUTO PROPERTIES ('replication_num'='1', 'enable_unique_key_merge_on_write'='true')", + "CREATE TABLE IF NOT EXISTS `db`.`custom_unique` (`id` INT, `val` INT) UNIQUE KEY (`id`) DISTRIBUTED BY HASH (`id`) BUCKETS 4 PROPERTIES ('enable_unique_key_merge_on_write'='false')", + ] + + +def test_ctas_reorders_key_columns_for_known_and_unknown_types( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + + adapter.ctas( + "db.known_ctas", + parse_one("SELECT payload, ds, id FROM db.src"), + { + "payload": exp.DataType.build("VARCHAR(50)"), + "ds": exp.DataType.build("DATE"), + "id": exp.DataType.build("INT"), + }, + table_properties={"unique_key": parse_one("(id, ds)")}, + ) + + adapter.ctas( + "db.unknown_ctas", + parse_one("SELECT payload, ds, id FROM db.src LIMIT 0"), + table_properties={"unique_key": parse_one("(id, ds)")}, + ) + + assert to_sql_calls(adapter) == [ + "CREATE TABLE IF NOT EXISTS `db`.`known_ctas` UNIQUE KEY (`id`, `ds`) DISTRIBUTED BY HASH (`id`, `ds`) BUCKETS AUTO PROPERTIES ('enable_unique_key_merge_on_write'='true') AS SELECT CAST(`id` AS INT) AS `id`, CAST(`ds` AS DATE) AS `ds`, CAST(`payload` AS VARCHAR(50)) AS `payload` FROM (SELECT `payload`, `ds`, `id` FROM `db`.`src`) AS `_subquery`", + "CREATE TABLE IF NOT EXISTS `db`.`unknown_ctas` UNIQUE KEY (`id`, `ds`) DISTRIBUTED BY HASH (`id`, `ds`) BUCKETS AUTO PROPERTIES ('enable_unique_key_merge_on_write'='true') AS SELECT `id`, `ds`, `payload` FROM (SELECT `payload`, `ds`, `id` FROM `db`.`src` LIMIT 0) AS `_subquery`", + ] + + +def test_create_table_partitions_and_distribution(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + + adapter.create_table( + "db.ranged", + {"id": exp.DataType.build("INT"), "ds": exp.DataType.build("DATE")}, + table_properties={ + "duplicate_key": exp.Literal.string("id, ds"), + "partition_by": parse_one("RANGE(ds)"), + "partitions": parse_one("('PARTITION p1 VALUES LESS THAN (\"2025-01-01\")')"), + "distributed_by": exp.Literal.string("HASH(id) BUCKETS 8"), + }, + ) + + adapter.create_table( + "db.listed", + {"id": exp.DataType.build("INT"), "region": exp.DataType.build("VARCHAR(20)")}, + partitioned_by=[parse_one("id")], + table_properties={ + "duplicate_key": parse_one("(id, region)"), + "partition_by": parse_one("LIST(region)"), + "partitions": exp.Literal.string('PARTITION p_us VALUES IN ("us")'), + "distributed_by": exp.Literal.string("RANDOM"), + }, + ) + + assert to_sql_calls(adapter) == [ + 'CREATE TABLE IF NOT EXISTS `db`.`ranged` (`id` INT, `ds` DATE) DUPLICATE KEY (`id`, `ds`) PARTITION BY RANGE (`ds`) (PARTITION p1 VALUES LESS THAN ("2025-01-01")) DISTRIBUTED BY HASH (`id`) BUCKETS 8', + 'CREATE TABLE IF NOT EXISTS `db`.`listed` (`id` INT, `region` VARCHAR(20)) DUPLICATE KEY (`id`, `region`) PARTITION BY LIST (`region`) (PARTITION p_us VALUES IN ("us")) DISTRIBUTED BY RANDOM', + ] + + +def test_create_table_validation_errors(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + cols = {"id": exp.DataType.build("INT"), "val": exp.DataType.build("INT")} + + with pytest.raises(SQLMeshError, match="PRIMARY KEY"): + adapter.create_table("t", cols, primary_key=("id",)) + + with pytest.raises(SQLMeshError, match="PRIMARY KEY"): + adapter.create_table("t", cols, table_properties={"primary_key": parse_one("id")}) + + with pytest.raises(SQLMeshError, match="AGGREGATE KEY"): + adapter.create_table("t", cols, table_properties={"aggregate_key": parse_one("id")}) + + with pytest.raises(SQLMeshError, match="both `unique_key` and `duplicate_key`"): + adapter.create_table( + "t", + cols, + table_properties={"unique_key": parse_one("id"), "duplicate_key": parse_one("id")}, + ) + + with pytest.raises(SQLMeshError, match="not found in table columns"): + adapter.create_table("t", cols, table_properties={"unique_key": parse_one("missing_col")}) + + +def test_delete_from_truncates_unconditional(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + + adapter.delete_from("db.t", exp.true()) + adapter.delete_from("db.t", "TRUE") + adapter.delete_from("db.t", "id = 1") + + assert to_sql_calls(adapter) == [ + "TRUNCATE TABLE `db`.`t`", + "TRUNCATE TABLE `db`.`t`", + "DELETE FROM `db`.`t` WHERE `id` = 1", + ] + + +def test_replace_by_key_uses_concat_ws_subquery( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +): + """Doris must NOT emit MySQL's incompatible DELETE _target FROM ... INNER JOIN.""" + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + temp_table_mock = mocker.patch("sqlmesh.core.engine_adapter.base.EngineAdapter._get_temp_table") + temp_table_mock.return_value = exp.to_table("db.temp_tbl") + + adapter.merge( + target_table="db.target", + source_table=t.cast(exp.Select, parse_one("SELECT id, ts, val FROM db.source")), + target_columns_to_types={ + "id": exp.DataType.build("INT"), + "ts": exp.DataType.build("DATETIME"), + "val": exp.DataType.build("INT"), + }, + unique_key=[parse_one("id"), parse_one("ts")], + ) + + sql_calls = to_sql_calls(adapter) + assert any("INNER JOIN" in sql for sql in sql_calls) is False + assert any("CONCAT_WS" in sql and " IN (" in sql for sql in sql_calls) is True + adapter.cursor.execute.assert_has_calls( + [ + call( + "DELETE FROM `db`.`target` WHERE CONCAT_WS('__SQLMESH_DELIM__', `id`, `ts`) IN (SELECT CONCAT_WS('__SQLMESH_DELIM__', `id`, `ts`) FROM `db`.`temp_tbl`)" + ) + ] + ) + + +def test_adjust_physical_properties_for_incremental(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + + # Promotes unique_key for INCREMENTAL_BY_UNIQUE_KEY + promoted = adapter.adjust_physical_properties_for_incremental( + {}, + requires_delete_capable_table=True, + unique_key=[exp.column("id"), exp.column("ds")], + model_name="db.m", + ) + assert isinstance(promoted["unique_key"], exp.Tuple) + + # Keeps explicit unique_key intact + existing = {"unique_key": parse_one("(id)")} + assert ( + adapter.adjust_physical_properties_for_incremental( + existing, + requires_delete_capable_table=True, + unique_key=None, + model_name="db.m", + ) + is existing + ) + + # Non-delete-capable (append-only) skips requirement + assert ( + adapter.adjust_physical_properties_for_incremental( + {}, + requires_delete_capable_table=False, + unique_key=None, + model_name="db.m", + ) + == {} + ) + + # Missing unique_key on incremental model fails clearly + with pytest.raises(SQLMeshError, match="requires a UNIQUE KEY table"): + adapter.adjust_physical_properties_for_incremental( + {}, + requires_delete_capable_table=True, + unique_key=None, + model_name="db.m", + ) + + +def test_comments(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + + adapter.create_table( + "test_table", + {"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")}, + table_description="table desc", + column_descriptions={"a": "col desc"}, + ) + adapter.ctas( + "test_ctas", + parse_one("SELECT a, b FROM source_table"), + {"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")}, + table_description="ctas desc", + column_descriptions={"a": "ctas col desc"}, + ) + adapter.create_view( + "test_view", + parse_one("SELECT a, b FROM source_table"), + target_columns_to_types={"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")}, + table_description="view desc", + column_descriptions={"a": "view col desc"}, + ) + adapter._create_table_comment("test_table", "new table desc") + adapter._create_column_comments("test_table", {"a": "new col desc"}) + + assert to_sql_calls(adapter) == [ + "CREATE TABLE IF NOT EXISTS `test_table` (`a` INT COMMENT 'col desc', `b` INT) COMMENT 'table desc'", + "CREATE TABLE IF NOT EXISTS `test_ctas` COMMENT 'ctas desc' AS SELECT CAST(`a` AS INT) AS `a`, CAST(`b` AS INT) AS `b` FROM (SELECT `a`, `b` FROM `source_table`) AS `_subquery`", + "ALTER TABLE `test_ctas` MODIFY COLUMN `a` COMMENT 'ctas col desc'", + "CREATE OR REPLACE VIEW `test_view` (`a` COMMENT 'view col desc', `b`) COMMENT 'view desc' AS SELECT `a`, `b` FROM `source_table`", + "ALTER TABLE `test_table` MODIFY COMMENT 'new table desc'", + "ALTER TABLE `test_table` MODIFY COLUMN `a` COMMENT 'new col desc'", + ] + + +def test_create_index_noop_and_rename_table(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + adapter.create_index("db.t", "idx_a", ("a",)) + adapter.rename_table("db.old_t", "db.new_t") + + assert to_sql_calls(adapter) == [ + "ALTER TABLE `db`.`old_t` RENAME `new_t`", + ] + + +def test_alter_table_waits_for_schema_change( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + adapter.cursor.description = [("JobId",), ("State",), ("Msg",)] + adapter.cursor.fetchone.side_effect = [ + ("1", "RUNNING", ""), + ("1", "FINISHED", ""), + ("2", "FINISHED", ""), + ] + mocker.patch("sqlmesh.core.engine_adapter.doris.time.sleep") + + int_t = exp.DataType.build("INT") + add_ops = adapter.schema_differ.compare_columns( + "db.t", {"id": int_t, "old_c": int_t}, {"id": int_t, "old_c": int_t, "c": int_t} + ) + drop_ops = adapter.schema_differ.compare_columns( + "db.t", {"id": int_t, "old_c": int_t, "c": int_t}, {"id": int_t, "c": int_t} + ) + adapter.alter_table(add_ops + drop_ops) + + assert to_sql_calls(adapter) == [ + "ALTER TABLE `db`.`t` ADD COLUMN `c` INT", + "SHOW ALTER TABLE COLUMN FROM `db` WHERE TableName = 't' ORDER BY CreateTime DESC LIMIT 1", + "SHOW ALTER TABLE COLUMN FROM `db` WHERE TableName = 't' ORDER BY CreateTime DESC LIMIT 1", + "ALTER TABLE `db`.`t` DROP COLUMN `old_c`", + "SHOW ALTER TABLE COLUMN FROM `db` WHERE TableName = 't' ORDER BY CreateTime DESC LIMIT 1", + ] + + +def test_alter_table_raises_on_cancelled_schema_change(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + adapter.cursor.description = [("JobId",), ("State",), ("Msg",)] + adapter.cursor.fetchone.return_value = ("1", "CANCELLED", "incompatible change") + + int_t = exp.DataType.build("INT") + add_ops = adapter.schema_differ.compare_columns( + "db.t", {"id": int_t}, {"id": int_t, "c": int_t} + ) + with pytest.raises(SQLMeshError, match="cancelled"): + adapter.alter_table(add_ops) + + +def test_alter_table_raises_on_timeout( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + adapter.cursor.description = [("JobId",), ("State",), ("Msg",)] + adapter.cursor.fetchone.return_value = ("1", "RUNNING", "") + mocker.patch("sqlmesh.core.engine_adapter.doris.time.sleep") + mocker.patch("sqlmesh.core.engine_adapter.doris.time.monotonic", side_effect=[0.0, 100.0]) + + int_t = exp.DataType.build("INT") + add_ops = adapter.schema_differ.compare_columns( + "db.t", {"id": int_t}, {"id": int_t, "c": int_t} + ) + with pytest.raises(SQLMeshError, match="Timed out waiting for Doris schema change"): + adapter.alter_table(add_ops) diff --git a/tests/core/test_connection_config.py b/tests/core/test_connection_config.py index d0ba023273..2ca5bd7182 100644 --- a/tests/core/test_connection_config.py +++ b/tests/core/test_connection_config.py @@ -16,6 +16,7 @@ ClickhouseConnectionConfig, ConnectionConfig, DatabricksConnectionConfig, + DorisConnectionConfig, DuckDBAttachOptions, DuckDBConnectionConfig, FabricConnectionConfig, @@ -2585,3 +2586,60 @@ def test_starrocks(make_config): assert advanced_config.charset == "utf8mb4" assert advanced_config.ssl_disabled is True assert advanced_config.concurrent_tasks == 10 + + +def test_doris(make_config): + """Test DorisConnectionConfig defaults, options, and state sync status.""" + from sqlmesh.core.engine_adapter import DorisEngineAdapter + + config = make_config( + type="doris", + host="doris-fe", + user="admin", + check_import=False, + ) + assert isinstance(config, DorisConnectionConfig) + assert config.type_ == "doris" + assert config.port == 9030 + assert config.password == "" + assert config.connect_timeout == 10 + assert config.DIALECT == "doris" + assert config.DISPLAY_NAME == "Apache Doris" + assert config.DISPLAY_ORDER == 20 + assert config.is_forbidden_for_state_sync is True + assert config.is_recommended_for_state_sync is False + assert isinstance(config.create_engine_adapter(), DorisEngineAdapter) + + advanced_config = make_config( + type="doris", + host="doris-fe", + user="admin", + password="secret", + port=9031, + database="analytics", + charset="utf8mb4", + collation="utf8mb4_unicode_ci", + ssl_disabled=True, + connect_timeout=30, + concurrent_tasks=8, + check_import=False, + ) + assert advanced_config.port == 9031 + assert advanced_config.database == "analytics" + assert advanced_config.charset == "utf8mb4" + assert advanced_config.collation == "utf8mb4_unicode_ci" + assert advanced_config.ssl_disabled is True + assert advanced_config.connect_timeout == 30 + assert advanced_config.concurrent_tasks == 8 + assert { + "host", + "user", + "password", + "port", + "database", + "charset", + "collation", + "ssl_disabled", + "connect_timeout", + "local_infile", + }.issubset(advanced_config._connection_kwargs_keys) From 89f65d322e35066edd0f460671d272cbcb5e915f Mon Sep 17 00:00:00 2001 From: Bruce Arctor <5032356+brucearctor@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:32:10 -0800 Subject: [PATCH 2/2] fix(doris): address PR review findings --- .github/scripts/wait-for-db.sh | 13 +++++++++-- docs/integrations/engines/doris.md | 2 +- sqlmesh/core/engine_adapter/doris.py | 22 +++++++++++++++++-- tests/core/engine_adapter/test_doris.py | 29 +++++++++++++++++++++++++ tests/core/test_connection_config.py | 7 +++++- 5 files changed, 67 insertions(+), 6 deletions(-) diff --git a/.github/scripts/wait-for-db.sh b/.github/scripts/wait-for-db.sh index 07806fcdff..fcef040ef0 100755 --- a/.github/scripts/wait-for-db.sh +++ b/.github/scripts/wait-for-db.sh @@ -82,10 +82,19 @@ starrocks_ready() { } doris_ready() { - probe_port 9030 + 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..." - local deadline=$((SECONDS + 180)) 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" diff --git a/docs/integrations/engines/doris.md b/docs/integrations/engines/doris.md index a718384760..b368407de6 100644 --- a/docs/integrations/engines/doris.md +++ b/docs/integrations/engines/doris.md @@ -36,7 +36,7 @@ gateways: # connect_timeout: 10 state_connection: type: duckdb - database: ./state/sqlmesh_state.db + database: ./sqlmesh_state.db default_gateway: doris diff --git a/sqlmesh/core/engine_adapter/doris.py b/sqlmesh/core/engine_adapter/doris.py index 22f38fe4d6..3c526fed06 100644 --- a/sqlmesh/core/engine_adapter/doris.py +++ b/sqlmesh/core/engine_adapter/doris.py @@ -103,6 +103,15 @@ def adjust_physical_properties_for_incremental( return physical_properties if unique_key: + invalid_keys = [ + k for k in unique_key if not isinstance(k, (exp.Column, exp.Identifier)) + ] + if invalid_keys: + raise SQLMeshError( + f"Doris incremental model '{model_name}' requires plain column names in `unique_key`; " + f"got expression(s): {[k.sql(dialect=self.dialect) for k in invalid_keys]}. " + "Project the expression as a named column or specify `physical_properties (unique_key = (...))`." + ) physical_properties["unique_key"] = ( unique_key[0] if len(unique_key) == 1 else exp.Tuple(expressions=unique_key) ) @@ -479,9 +488,18 @@ def _reorder_query_for_key( if not isinstance(query, exp.Query) or query.parent is not None: return t.cast(exp.Query, query) - selects = [col for col in query.named_selects if col != "*"] - if not selects or selects[: len(key_columns)] == list(key_columns): + named_selects = query.named_selects + has_wildcard = "*" in named_selects + selects = [col for col in named_selects if col != "*"] + if not selects or (not has_wildcard and selects[: len(key_columns)] == list(key_columns)): return query + if has_wildcard: + if named_selects[: len(key_columns)] == list(key_columns): + return query + raise SQLMeshError( + f"Cannot reorder Doris `{key_type}` columns {list(key_columns)} for a CTAS query " + "containing wildcard (`*`) projections. Select columns explicitly or declare model column types." + ) missing = [c for c in key_columns if c not in selects] if missing: diff --git a/tests/core/engine_adapter/test_doris.py b/tests/core/engine_adapter/test_doris.py index 341a9e6733..3c9c6b94a6 100644 --- a/tests/core/engine_adapter/test_doris.py +++ b/tests/core/engine_adapter/test_doris.py @@ -101,6 +101,26 @@ def test_ctas_reorders_key_columns_for_known_and_unknown_types( ] +def test_ctas_wildcard_projection_with_unique_key(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DorisEngineAdapter) + + adapter.ctas( + "db.prefix_star", + parse_one("SELECT id, s.* FROM db.src AS s"), + table_properties={"unique_key": parse_one("id")}, + ) + assert to_sql_calls(adapter) == [ + "CREATE TABLE IF NOT EXISTS `db`.`prefix_star` UNIQUE KEY (`id`) DISTRIBUTED BY HASH (`id`) BUCKETS AUTO PROPERTIES ('enable_unique_key_merge_on_write'='true') AS SELECT `id`, `s`.* FROM `db`.`src` AS `s`", + ] + + with pytest.raises(SQLMeshError, match="wildcard"): + adapter.ctas( + "db.non_prefix_star", + parse_one("SELECT 1 AS version, 2 AS id, s.* FROM db.src AS s"), + table_properties={"unique_key": parse_one("id")}, + ) + + def test_create_table_partitions_and_distribution(make_mocked_engine_adapter: t.Callable): adapter = make_mocked_engine_adapter(DorisEngineAdapter) @@ -246,6 +266,15 @@ def test_adjust_physical_properties_for_incremental(make_mocked_engine_adapter: model_name="db.m", ) + # Expression unique_key fails with an error naming the model + with pytest.raises(SQLMeshError, match="db.m.*plain column names"): + adapter.adjust_physical_properties_for_incremental( + {}, + requires_delete_capable_table=True, + unique_key=[parse_one("COALESCE(id, 0)")], + model_name="db.m", + ) + def test_comments(make_mocked_engine_adapter: t.Callable): adapter = make_mocked_engine_adapter(DorisEngineAdapter) diff --git a/tests/core/test_connection_config.py b/tests/core/test_connection_config.py index 2ca5bd7182..6136a4f21b 100644 --- a/tests/core/test_connection_config.py +++ b/tests/core/test_connection_config.py @@ -2588,7 +2588,7 @@ def test_starrocks(make_config): assert advanced_config.concurrent_tasks == 10 -def test_doris(make_config): +def test_doris(make_config, monkeypatch): """Test DorisConnectionConfig defaults, options, and state sync status.""" from sqlmesh.core.engine_adapter import DorisEngineAdapter @@ -2608,6 +2608,11 @@ def test_doris(make_config): assert config.DISPLAY_ORDER == 20 assert config.is_forbidden_for_state_sync is True assert config.is_recommended_for_state_sync is False + monkeypatch.setattr( + DorisConnectionConfig, + "_connection_factory", + property(lambda self: lambda **kwargs: None), + ) assert isinstance(config.create_engine_adapter(), DorisEngineAdapter) advanced_config = make_config(