diff --git a/docs/connection-integration/data-integration/intro.mdx b/docs/connection-integration/data-integration/intro.mdx
index 2c865cf42b443e..e623e2ea12e050 100644
--- a/docs/connection-integration/data-integration/intro.mdx
+++ b/docs/connection-integration/data-integration/intro.mdx
@@ -271,4 +271,22 @@ Apache Doris supports integration with a wide range of data ecosystem tools. You
description="Use the JDBC Engine of Apache Kyuubi to integrate Doris as a SQL query data source"
link="./kyuubi"
/>
+
+
+
+{/* Official wordmark: https://github.com/tobymao/sqlglot/blob/main/sqlglot.png.
+ Keep the original asset; display its left-hand symbol in the square card icon. */}
+
diff --git a/docs/connection-integration/data-integration/sqlglot.md b/docs/connection-integration/data-integration/sqlglot.md
new file mode 100644
index 00000000000000..58ebafae6d5725
--- /dev/null
+++ b/docs/connection-integration/data-integration/sqlglot.md
@@ -0,0 +1,482 @@
+---
+{
+ "title": "Convert SQL with SQLGlot",
+ "sidebar_label": "SQLGlot",
+ "language": "en",
+ "description": "Convert PostgreSQL, ClickHouse, Hive, and other SQL dialects to Doris SQL with SQLGlot, and develop an HTTP conversion service for Doris."
+}
+---
+
+## Overview
+
+Migrating queries from PostgreSQL or other databases to Apache Doris requires adapting dialect differences in functions, data types, and identifiers. [SQLGlot](https://github.com/tobymao/sqlglot) provides SQL parsing and dialect conversion to help convert source queries to Doris SQL and reduce manual rewriting.
+
+SQLGlot is implemented in Python and supports source dialects including PostgreSQL, ClickHouse, Hive, Spark, BigQuery, and Snowflake.
+
+This guide uses the community `tobymao/sqlglot` project and covers two approaches:
+
+- **Standard usage**: convert SQL locally through the Python API or command line.
+- **Integration development**: develop an HTTP conversion service that receives requests from Doris FE and returns converted SQL for Doris to execute.
+
+For offline conversion, use the local API or command line. For Doris integration, use the HTTP example as a starting point and deploy and maintain the service for your environment.
+
+SQLGlot is maintained as an independent third-party project. Refer to its release notes for installation requirements and supported features. Execute generated SQL on your target Doris version and validate query results before migration.
+
+## Conversion Flow and Scope
+
+```text
+Source SQL from PostgreSQL / Hive / ClickHouse / ...
+ → Source dialect Parser: parse the SQL
+ → SQLGlot common AST: represent the query as an expression tree
+ → Doris Generator: generate SQL in the Doris dialect
+ → Doris SQL text
+```
+
+SQLGlot converts functions and expressions using built-in rules. Migration also requires the following separate work:
+
+- Migrate data, configure database connections, and execute the generated SQL.
+- Design Doris table models, partitions, buckets, and indexes for your workload.
+- Check function availability in the target version and deploy any required user-defined functions (UDFs).
+- Validate data types, session settings, and query results.
+
+This guide focuses on query conversion. Schema migration also requires adapting table definitions to Doris requirements.
+
+## Installation
+
+### Prerequisites
+
+Install Python and pip. Source installation also requires Git. Python 3.11 or later and an isolated virtual environment are recommended. Check the package metadata of your selected SQLGlot version for its minimum Python requirement.
+
+The following commands use macOS/Linux:
+
+```bash
+mkdir sqlglot-doris-demo
+cd sqlglot-doris-demo
+python3 -m venv .venv
+source .venv/bin/activate
+python -m pip install --upgrade pip
+```
+
+Downloading dependencies and source code requires network access. After installation, SQL conversion can run offline.
+
+### Option 1: Install an Official Release
+
+Install SQLGlot from PyPI and check the installed version:
+
+```bash
+python -m pip install "sqlglot==30.35.0"
+python -c "import sqlglot; print(sqlglot.__version__)"
+```
+
+This guide uses `30.35.0`. To use another version, replace the version number based on the [PyPI release history](https://pypi.org/project/sqlglot/#history). Pin your project dependency and run regression tests on representative queries after upgrading.
+
+### Option 2: Install from Official Source
+
+To debug conversion rules or use a specific source revision, run these commands in the activated virtual environment:
+
+```bash
+git clone --branch v30.35.0 --depth 1 https://github.com/tobymao/sqlglot.git sqlglot-source
+cd sqlglot-source
+python -m pip install -e .
+python -c "import sqlglot; print(sqlglot.__version__); print(sqlglot.__file__)"
+git rev-parse HEAD
+cd ..
+```
+
+Choose either release installation or source installation. The `-e .` option installs the current checkout in editable mode. Replace the Git tag when using another version. When using `main`, record the actual commit to reproduce conversion results.
+
+These commands install the pure Python version of SQLGlot, which supports local conversion. C extensions are optional, and Doris compilation and deployment are independent. SQLGlot also provides `make install` for editable installation; see the [SQLGlot installation instructions](https://github.com/tobymao/sqlglot#install).
+
+## Local Conversion
+
+Local conversion requires only the installed SQLGlot package. A Python API call or command-line invocation performs the conversion without starting a service or connecting to a database.
+
+### Use the Python API
+
+**Parse and generate in one call**
+
+Create `convert_sql.py` with the following code. Avoid naming the file `sqlglot.py`, which would conflict with the package name.
+
+```python
+import sqlglot
+from sqlglot.errors import ErrorLevel
+
+source_sql = "SELECT 'hello'::TEXT AS message"
+
+target_sql = sqlglot.transpile(
+ source_sql,
+ read="postgres",
+ write="doris",
+ pretty=True,
+ unsupported_level=ErrorLevel.RAISE,
+)[0]
+
+print(target_sql)
+```
+
+Run:
+
+```bash
+python convert_sql.py
+```
+
+Output:
+
+```sql
+SELECT
+ CAST('hello' AS STRING) AS message
+```
+
+The example converts PostgreSQL `::TEXT` to Doris `CAST(... AS STRING)` and returns SQL text.
+
+Key parameters:
+
+- `read="postgres"`: the source SQL dialect; match it to the actual input dialect.
+- `write="doris"`: the target SQL dialect.
+- `pretty=True`: format generated SQL with line breaks and indentation.
+- `unsupported_level=ErrorLevel.RAISE`: raise an exception for unsupported cases recognized by the converter.
+
+`transpile()` returns a list of SQL strings. The example contains one statement and uses `[0]` to retrieve it. For a multi-statement script, iterate over the returned list.
+
+**Parse and generate separately**
+
+To inspect or modify the abstract syntax tree (AST), call the parsing and generation interfaces separately:
+
+```python
+import sqlglot
+from sqlglot.errors import ErrorLevel
+
+source_sql = "SELECT 'hello'::TEXT AS message"
+tree = sqlglot.parse_one(source_sql, read="postgres")
+
+target_sql = tree.sql(
+ dialect="doris",
+ pretty=True,
+ unsupported_level=ErrorLevel.RAISE,
+)
+print(target_sql)
+```
+
+Both interfaces use SQLGlot's built-in dialect implementations and are available after installing the package.
+
+### Use the Command Line
+
+Convert PostgreSQL SQL to Doris SQL:
+
+```bash
+python -m sqlglot "SELECT 'hello'::TEXT AS message" --read postgres --write doris
+```
+
+The command line applies identifier quoting rules, for example adding backticks around the alias `message`. Identifier quoting can therefore differ from the Python API example.
+
+Use `-` to read SQL from standard input and write the result to a target file:
+
+```bash
+python -m sqlglot - --read postgres --write doris < input.sql > output.doris.sql
+```
+
+The `input.sql` file should contain SQL statements only. For PostgreSQL `psql` scripts, first handle client commands such as `\set` and `\copy`.
+
+The command line warns about some unsupported conversions by default; also check standard error. Use the Python API to configure `unsupported_level` or custom error handling. The CLI `--error-level` option controls parsing errors, while the API `unsupported_level` parameter controls unsupported-generation diagnostics.
+
+### Specify Other Source Dialects
+
+Keep the target as `doris` and select `read` for your actual input:
+
+- PostgreSQL: `read="postgres"`.
+- ClickHouse: `read="clickhouse"`.
+- Hive: `read="hive"`.
+- Spark SQL: `read="spark"`.
+- BigQuery: `read="bigquery"`.
+- Snowflake: `read="snowflake"`.
+
+Conversion coverage depends on the SQLGlot version and the target syntax and functions supported by Doris. For Hive and Spark SQL, select the dialect based on the actual execution engine.
+
+## Error Handling and Migration Validation
+
+Common conversion and execution issues include:
+
+- `ParseError`: check the `read` dialect, input SQL, and SQLGlot version. Confirm source SQL validity on the source database.
+- `UnsupportedError`: save the source SQL and full error message, then check the conversion rule and target-version support.
+- Doris execution failure: check functions, data types, syntax, and the database environment. Unknown functions may be preserved by name; confirm target support.
+- Result differences: check data, result types, NULLs, precision, time zones, and ordering settings on both engines.
+
+`unsupported_level=RAISE` raises errors only for unsupported cases the converter recognizes. Generated SQL still needs validation on Doris. `transpile()` does not query table schemas; type-dependent conversions may require schema information or type inference. See [SQLGlot conversion limitations](https://github.com/tobymao/sqlglot#unsupported-errors).
+
+Before migration, execute source and generated SQL against the same logical data with fixed session settings. Compare column types, row values, NULLs, duplicates, and final ordering. Also test boundary values for Decimal, floating-point, date/time, array, and JSON types.
+
+For data loading and ongoing synchronization, see the [Doris migration overview](../../migration/overview.md).
+
+## Develop an HTTP Conversion Service for Doris
+
+### Integration Flow and Responsibilities
+
+Wrap SQLGlot in an HTTP service for applications to call directly, or integrate it with the Doris dialect conversion entry point:
+
+```text
+Standalone conversion:
+Caller → HTTP service → SQLGlot → return Doris SQL text
+
+Doris integration:
+Client submits source-dialect SQL to Doris through the MySQL protocol
+ → FE selects the conversion entry point using sql_dialect
+ → FE sends an HTTP POST to sql_converter_service_url
+ → Your service calls SQLGlot and returns Doris SQL text
+ → FE parses and plans the query; Doris executes the converted SQL
+ → Client receives query results
+```
+
+The HTTP service receives SQL text and returns conversion results without database connections. Before executing table queries, migrate the data or configure an external catalog so Doris can access the required databases and tables.
+
+The following example accepts one query only. It does not support DDL, DML, EXPLAIN, multi-statement scripts, or client commands. Add validation, conversion rules, and tests before expanding the supported statement scope.
+
+### Doris Interface Contract
+
+Match the service interface to your deployed Doris version. For request formats and plugin configuration, refer to:
+
+- [HttpDialectUtils.java](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectUtils.java): HTTP requests, responses, and failure handling.
+- [HttpDialectConverterPlugin.java](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectConverterPlugin.java): service URL configuration and accepted source dialects.
+
+The example uses protocol `v1` at `/api/v1/convert`. FE sends HTTP POST with `Content-Type: application/json` and the following body:
+
+```json
+{
+ "version": "v1",
+ "sql_query": "SELECT 'hello'::TEXT AS message",
+ "from": "postgres",
+ "to": "doris",
+ "source": "text",
+ "case_sensitive": "0",
+ "enable_sql_convertor_features": [],
+ "config": "{}"
+}
+```
+
+`sql_query` contains the SQL to convert. The `from` and `to` fields map to SQLGlot's `read` and `write` parameters. The HTTP service handles the remaining fields according to the interface contract.
+
+On success, return HTTP 200 with:
+
+```json
+{
+ "version": "v1",
+ "data": "SELECT CAST('hello' AS STRING) AS message",
+ "code": 0,
+ "message": "Success"
+}
+```
+
+`data` is the generated SQL string, and `code=0` indicates conversion success. On conversion failure, return a nonzero `code` and explain the cause in `message`. For example, submitting two SELECT statements returns:
+
+```json
+{
+ "version": "v1",
+ "data": "",
+ "code": 1,
+ "message": "ValueError: Exactly one query is required"
+}
+```
+
+FastAPI returns HTTP 422 for request parameter or JSON validation failures.
+
+### Minimal Example
+
+This section uses FastAPI, Pydantic 2, and Uvicorn to implement a basic conversion endpoint for local development and integration testing. Production access control, resource limits, and monitoring are discussed at the end of this section.
+
+Return to the `sqlglot-doris-demo` directory, activate the virtual environment, and install dependencies:
+
+```bash
+source .venv/bin/activate
+python -m pip install "fastapi>=0.115,<1" "pydantic>=2,<3" "uvicorn>=0.30,<1"
+```
+
+Use the SQLGlot version installed earlier. After validation, run `python -m pip freeze > requirements.txt` to record dependency versions.
+
+Create `converter_server.py` with:
+
+```python
+import json
+from typing import Literal
+
+import sqlglot
+from fastapi import FastAPI
+from pydantic import BaseModel, ConfigDict, Field
+from sqlglot import exp
+from sqlglot.errors import ErrorLevel, SqlglotError
+
+app = FastAPI(title="SQL conversion example")
+READ_DIALECTS = {"postgres", "clickhouse", "hive", "spark", "bigquery", "snowflake"}
+
+
+class ConvertRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ version: Literal["v1"] = "v1"
+ sql_query: str = Field(min_length=1, max_length=100_000)
+ source_dialect: str = Field(alias="from")
+ target_dialect: Literal["doris"] = Field(default="doris", alias="to")
+ source: Literal["text"] = "text"
+ case_sensitive: Literal["0"] = "0"
+ enable_sql_convertor_features: list[str] = Field(default_factory=list)
+ config: str | None = None
+
+
+def convert_one(sql: str, read: str) -> str:
+ if read not in READ_DIALECTS:
+ raise ValueError(f"Unsupported source dialect: {read}")
+ statements = sqlglot.parse(sql, read=read, error_level=ErrorLevel.RAISE)
+ trees = [tree for tree in statements if tree is not None]
+ if len(trees) != 1:
+ raise ValueError("Exactly one query is required")
+ tree = trees[0]
+ excluded = (exp.DDL, exp.DML, exp.Command, exp.Into, exp.Lock)
+ if not isinstance(tree, exp.Query) or any(isinstance(node, excluded) for node in tree.walk()):
+ raise ValueError("Only a single query without DDL/DML, INTO or locking is supported")
+ return tree.sql(dialect="doris", unsupported_level=ErrorLevel.RAISE)
+
+
+def response(data: str = "", code: int = 0, message: str = "Success") -> dict:
+ return {"version": "v1", "data": data, "code": code, "message": message}
+
+
+@app.get("/healthz")
+def health() -> dict:
+ return {"status": "ok", "sqlglot_version": sqlglot.__version__}
+
+
+@app.post("/api/v1/convert")
+def convert(request: ConvertRequest) -> dict:
+ try:
+ enabled = [item for item in request.enable_sql_convertor_features if item.strip()]
+ config = json.loads(request.config) if request.config else {}
+ if enabled or config != {}:
+ raise ValueError("This example does not implement converter features or config")
+ return response(data=convert_one(request.sql_query, request.source_dialect))
+ except (SqlglotError, ValueError) as exc:
+ return response(code=1, message=f"{type(exc).__name__}: {exc}")
+ except Exception:
+ return response(code=1, message="Internal conversion error")
+```
+
+Implementation notes:
+
+- Each request parses and generates independently and returns the conversion result. No database driver or account is required.
+- `case_sensitive` accepts only `"0"` and uses SQLGlot's default dialect identifier rules. Add implementation and tests for other case-handling modes.
+- `enable_sql_convertor_features` accepts an empty list or blank string items only. `config` accepts `"{}"`, null, an empty string, or omission. Nonempty configuration and unknown fields are rejected.
+- Statement checks limit the input scope. A UDF in a SELECT can still have side effects; configure the required permissions in Doris.
+- `sql_query` is limited to 100,000 characters. Configure request-body byte limits, CPU and memory limits, and conversion timeouts separately.
+
+### Start and Test the Standalone Endpoint
+
+In the directory containing `converter_server.py`, start the service:
+
+```bash
+python -m uvicorn converter_server:app --host 127.0.0.1 --port 5001
+```
+
+The service runs in the foreground; press `Ctrl+C` to stop it. Binding to `127.0.0.1` allows access only from clients in the same host network environment.
+
+In another terminal, check its health:
+
+```bash
+curl --fail-with-body http://127.0.0.1:5001/healthz
+```
+
+Send a conversion request:
+
+```bash
+curl --fail-with-body http://127.0.0.1:5001/api/v1/convert \
+ -H 'Content-Type: application/json' \
+ --data-binary @- <<'JSON'
+{
+ "version": "v1",
+ "sql_query": "SELECT 'hello'::TEXT AS message",
+ "from": "postgres",
+ "to": "doris",
+ "source": "text",
+ "case_sensitive": "0",
+ "enable_sql_convertor_features": [],
+ "config": "{}"
+}
+JSON
+```
+
+On success, the response matches the JSON shown earlier, with generated Doris SQL in `data`. This verifies the conversion endpoint independently. `curl --fail-with-body` checks HTTP errors; also inspect `code` to determine conversion status.
+
+Direct endpoint calls can use all six source dialects in the example allowlist. Calls through Doris must also satisfy the built-in HTTP plugin's dialect restrictions, described next.
+
+### Configure Doris and Test the Integration
+
+Run the following in Doris to inspect the related variables:
+
+```sql
+SHOW GLOBAL VARIABLES LIKE 'sql_converter_service_url';
+SHOW VARIABLES LIKE 'sql_dialect';
+```
+
+Variable descriptions:
+
+- `sql_converter_service_url`: a global variable specifying the conversion service endpoint called by FE. Start the service before configuring this variable.
+- `sql_dialect`: a session variable specifying the dialect of SQL submitted on the current connection.
+
+Use an account with the required permissions to configure the service URL. This example assumes FE and the service share the same host network environment:
+
+```sql
+SET GLOBAL sql_converter_service_url = 'http://127.0.0.1:5001/api/v1/convert';
+```
+
+For cross-host or container deployment, use a hostname or network address reachable by FE and configure the service bind address and firewall. Inside Docker, `127.0.0.1` refers to the container itself; configure an appropriate address to reach a host service. The example has no authentication; restrict access to a controlled network.
+
+Connect to the Doris FE query port with a MySQL client:
+
+```bash
+mysql -h -P -u -p
+```
+
+Replace ``, ``, and `` with your settings. The query port defaults to 9030. Set the dialect and run the query in the same connection:
+
+```sql
+SET sql_dialect = 'postgres';
+SELECT 'hello'::TEXT AS message;
+SET sql_dialect = 'doris';
+```
+
+On success, Doris returns one row with `message` equal to `hello`. This constant query verifies the path from FE through the conversion service to generated-SQL execution. Validate business queries with their actual tables and data.
+
+The example service rejects SET and other non-query statements. Doris's HTTP conversion implementation may fall back to the original statement and process it with native syntax. Confirm this behavior in your deployed version before switching and restoring session dialects.
+
+The referenced Doris HTTP plugin accepts `presto`, `trino`, `hive`, `spark`, `postgres`, `clickhouse`, and `starrocks`; BigQuery and Snowflake are not listed. The dialects jointly supported by that plugin and this example are PostgreSQL, ClickHouse, Hive, and Spark. Extend `READ_DIALECTS` and add tests before accepting Presto, Trino, or StarRocks requests. Check the deployed version for the actual plugin dialect list.
+
+After testing, restore the session dialect to `doris`. To remove the service URL configuration, have an administrator restore its previous global value.
+
+### Failure Fallback and Production Considerations
+
+The referenced `HttpDialectUtils` logs failures and returns the original SQL when an HTTP request fails, the response `code` is nonzero, the protocol version does not match, or a request exception occurs. Doris may then parse the original SQL as native syntax. Client errors may come from that later stage; check both service responses and FE logs.
+
+When using this fallback behavior:
+
+- `unsupported_level=RAISE` controls conversion errors inside the service only. Configure database read/write permissions in Doris.
+- If the original SQL is compatible with Doris, it may execute successfully after fallback. Use the `::TEXT` example above and check that the service actually received a request.
+- If conversion failure must stop execution, add the necessary control in the caller, proxy, or Doris integration layer.
+
+Before production deployment, add and validate:
+
+1. **Compatibility tests**: pin SQLGlot and Doris versions; cover valid input, NULL, invalid input, empty input, multiple statements, DDL/DML, unimplemented parameters, and concurrent requests. Compare local API and HTTP outputs.
+2. **Resource and availability controls**: limit request size, complexity, concurrency, and queue time. Use terminable worker processes when conversion must stop on timeout; a thread may keep running after its caller times out.
+3. **FE request behavior**: the referenced HTTP utility does not explicitly configure connection or read timeouts. Synchronous requests may increase query latency. Verify network timeouts, connection failures, and service unavailability in your deployed version.
+4. **Access control and transport security**: restrict request sources and configure a gateway and TLS as needed. Before adding endpoint authentication, confirm that the FE client can send the required credentials; the referenced request implementation does not set custom authentication headers.
+5. **Logging and monitoring**: record request identifiers, versions, latency, success rates, and error types. SQL and exception text may contain sensitive information; configure redaction and log access controls.
+
+Implement these production capabilities on top of the example. Conversion coverage depends on SQLGlot rules and the Doris version; validate business-query compatibility after HTTP integration.
+
+## References
+
+- [SQLGlot repository and installation instructions](https://github.com/tobymao/sqlglot#install)
+- [SQLGlot Python API documentation](https://sqlglot.com/sqlglot.html)
+- [SQLGlot PyPI package](https://pypi.org/project/sqlglot/)
+- [SQLGlot command-line implementation](https://github.com/tobymao/sqlglot/blob/main/sqlglot/__main__.py)
+- [SQLGlot supported dialects](https://github.com/tobymao/sqlglot#supported-dialects)
+- [Doris HTTP protocol and failure fallback](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectUtils.java)
+- [Doris HTTP conversion plugin](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectConverterPlugin.java)
+- [Doris global variable definitions](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/qe/GlobalVariable.java)
+- [FastAPI introduction](https://fastapi.tiangolo.com/tutorial/first-steps/)
+- [Pydantic fields and aliases](https://docs.pydantic.dev/latest/concepts/fields/)
diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/connection-integration/data-integration/intro.mdx b/i18n/zh-CN/docusaurus-plugin-content-docs/current/connection-integration/data-integration/intro.mdx
index cb481d8386fb2c..2f4bf12f8c6771 100644
--- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/connection-integration/data-integration/intro.mdx
+++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/connection-integration/data-integration/intro.mdx
@@ -271,4 +271,22 @@ Apache Doris 支持与多类数据生态工具集成。您可以按照使用场
description="通过 Apache Kyuubi 的 JDBC Engine 将 Doris 作为 SQL 查询数据源接入"
link="./kyuubi"
/>
+
+
+
+{/* Official wordmark: https://github.com/tobymao/sqlglot/blob/main/sqlglot.png.
+ Keep the original asset; display its left-hand symbol in the square card icon. */}
+
diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/connection-integration/data-integration/sqlglot.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/connection-integration/data-integration/sqlglot.md
new file mode 100644
index 00000000000000..985e3b02797ea3
--- /dev/null
+++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/connection-integration/data-integration/sqlglot.md
@@ -0,0 +1,482 @@
+---
+{
+ "title": "使用 SQLGlot 转换 SQL",
+ "sidebar_label": "SQLGlot",
+ "language": "zh-CN",
+ "description": "使用 SQLGlot 将 PostgreSQL、ClickHouse、Hive 等方言的 SQL 转换为 Doris SQL,并开发 HTTP 转换服务接入 Doris。"
+}
+---
+
+## 概述
+
+将 PostgreSQL 等数据库中的查询迁移到 Apache Doris 时,需要适配函数、数据类型和标识符等方言差异。[SQLGlot](https://github.com/tobymao/sqlglot) 提供 SQL 解析和方言转换功能,可将源 SQL 转换为 Doris SQL,减少查询迁移中的手工改写工作。
+
+SQLGlot 使用 Python 实现,支持 PostgreSQL、ClickHouse、Hive、Spark、BigQuery 和 Snowflake 等源方言。
+
+本文基于社区版 `tobymao/sqlglot`,介绍以下两种使用方式:
+
+- **标准用法**:通过 Python API 或命令行在本地转换 SQL。
+- **开发集成**:开发 HTTP 转换服务,接收 Doris FE 的请求并返回转换后的 SQL,由 Doris 执行查询。
+
+离线转换可直接使用本地 API 或命令行。需要接入 Doris 时,可参考 HTTP 服务开发示例,按实际环境完成部署和维护。
+
+说明:SQLGlot 由独立的第三方项目维护,安装要求和功能支持以该项目的发布说明为准。迁移前请在目标 Doris 版本中执行生成的 SQL,并校验查询结果。
+
+## 转换流程与适用范围
+
+```text
+PostgreSQL / Hive / ClickHouse 等源 SQL
+ → 指定源方言的 Parser:解析 SQL
+ → SQLGlot 公共 AST:用表达式树表示查询
+ → Doris Generator:按照 Doris 方言生成 SQL
+ → Doris SQL 文本
+```
+
+SQLGlot 按内置规则转换函数和表达式。迁移时还需单独完成以下工作:
+
+- 迁移数据,配置数据库连接并执行生成的 SQL。
+- 根据业务设计 Doris 表模型、分区、分桶和索引。
+- 检查目标版本的函数支持情况,部署查询依赖的 UDF。
+- 校验数据类型、Session 设置和查询结果。
+
+本文主要介绍查询转换。表结构迁移还需结合 Doris 的建表要求进行调整。
+
+## 安装
+
+### 环境准备
+
+安装前请准备 Python 和 pip。从源码安装还需要 Git。建议使用 Python 3.11 或更高版本,并创建独立虚拟环境。最低 Python 版本要求请参阅所选 SQLGlot 版本的包信息。
+
+以下命令以 macOS/Linux 为例:
+
+```bash
+mkdir sqlglot-doris-demo
+cd sqlglot-doris-demo
+python3 -m venv .venv
+source .venv/bin/activate
+python -m pip install --upgrade pip
+```
+
+下载依赖和源码需要网络连接。安装完成后,可在离线环境中转换 SQL。
+
+### 方式一:安装官方发布版
+
+通过 PyPI 安装 SQLGlot,并检查安装版本:
+
+```bash
+python -m pip install "sqlglot==30.35.0"
+python -c "import sqlglot; print(sqlglot.__version__)"
+```
+
+本文以 `30.35.0` 为例。使用其他版本时,请根据 [PyPI 发布历史](https://pypi.org/project/sqlglot/#history)替换版本号。建议固定项目依赖版本,升级后对代表性 SQL 进行回归测试。
+
+### 方式二:从官方源码安装
+
+如需调试转换逻辑或使用指定源码版本,可在已激活的虚拟环境中执行以下命令:
+
+```bash
+git clone --branch v30.35.0 --depth 1 https://github.com/tobymao/sqlglot.git sqlglot-source
+cd sqlglot-source
+python -m pip install -e .
+python -c "import sqlglot; print(sqlglot.__version__); print(sqlglot.__file__)"
+git rev-parse HEAD
+cd ..
+```
+
+发布版安装和源码安装任选一种。`-e .` 表示以可编辑方式安装当前目录的源码。使用其他版本时,请替换 Git 标签;使用 `main` 分支时,请记录实际提交号,便于复现转换结果。
+
+上述命令安装 SQLGlot 的纯 Python 版本,可直接用于本地转换。C 扩展为可选依赖,Doris 的编译和部署可独立进行。SQLGlot 官方也提供 `make install` 命令执行可编辑安装,详见 [SQLGlot 安装说明](https://github.com/tobymao/sqlglot#install)。
+
+## 本地转换
+
+本地转换仅依赖已安装的 SQLGlot 包,通过一次 Python 调用或命令行运行即可完成。转换过程中无需启动服务或连接数据库。
+
+### 使用 Python API
+
+**一步完成解析与生成**
+
+创建 `convert_sql.py`,写入以下代码。请避免使用 `sqlglot.py` 作为文件名,以免与 SQLGlot 包发生名称冲突。
+
+```python
+import sqlglot
+from sqlglot.errors import ErrorLevel
+
+source_sql = "SELECT 'hello'::TEXT AS message"
+
+target_sql = sqlglot.transpile(
+ source_sql,
+ read="postgres",
+ write="doris",
+ pretty=True,
+ unsupported_level=ErrorLevel.RAISE,
+)[0]
+
+print(target_sql)
+```
+
+运行:
+
+```bash
+python convert_sql.py
+```
+
+输出:
+
+```sql
+SELECT
+ CAST('hello' AS STRING) AS message
+```
+
+示例将 PostgreSQL 的 `::TEXT` 转换为 Doris 的 `CAST(... AS STRING)`,返回生成的 SQL 文本。
+
+主要参数含义:
+
+- `read="postgres"`:源 SQL 方言,需与输入语句的实际方言一致。
+- `write="doris"`:目标 SQL 方言。
+- `pretty=True`:对生成的 SQL 进行换行和缩进。
+- `unsupported_level=ErrorLevel.RAISE`:遇到转换器已识别的不支持情况时抛出异常。
+
+`transpile()` 返回 SQL 字符串列表。上例包含一条语句,使用 `[0]` 取得转换结果。处理多语句脚本时,请遍历返回列表。
+
+**分开解析与生成**
+
+如需查看或修改 AST,可分别调用解析和生成接口:
+
+```python
+import sqlglot
+from sqlglot.errors import ErrorLevel
+
+source_sql = "SELECT 'hello'::TEXT AS message"
+tree = sqlglot.parse_one(source_sql, read="postgres")
+
+target_sql = tree.sql(
+ dialect="doris",
+ pretty=True,
+ unsupported_level=ErrorLevel.RAISE,
+)
+print(target_sql)
+```
+
+上述接口均使用 SQLGlot 内置的方言实现,安装 SQLGlot 后即可调用。
+
+### 使用命令行
+
+执行以下命令,将 PostgreSQL SQL 转换为 Doris SQL:
+
+```bash
+python -m sqlglot "SELECT 'hello'::TEXT AS message" --read postgres --write doris
+```
+
+命令行会根据标识符引用规则添加反引号,例如为别名 message 添加反引号。生成结果中的标识符引用方式可能与 Python API 示例有所不同。
+
+使用 `-` 从标准输入读取 SQL 文件,并将转换结果写入目标文件:
+
+```bash
+python -m sqlglot - --read postgres --write doris < input.sql > output.doris.sql
+```
+
+`input.sql` 应仅包含 SQL 语句。使用 PostgreSQL `psql` 脚本时,请先处理 `\set`、`\copy` 等客户端命令。
+
+命令行默认对部分不支持的转换输出警告,请同时检查标准错误输出。需要配置 `unsupported_level` 或自定义错误处理时,请使用 Python API。命令行参数 `--error-level` 用于控制解析错误级别,API 参数 `unsupported_level` 用于控制生成阶段的不支持诊断。
+
+### 指定其他源方言
+
+目标保持 `doris`,按实际输入替换 `read`:
+
+- PostgreSQL:`read="postgres"`。
+- ClickHouse:`read="clickhouse"`。
+- Hive:`read="hive"`。
+- Spark SQL:`read="spark"`。
+- BigQuery:`read="bigquery"`。
+- Snowflake:`read="snowflake"`。
+
+各方言的转换范围取决于 SQLGlot 版本及 Doris 对目标语法和函数的支持情况。Hive 和 Spark SQL 请按实际执行引擎选择方言。
+
+## 错误处理与迁移验证
+
+转换和执行过程中,常见问题及处理方式如下:
+
+- `ParseError`:检查 `read` 方言、输入 SQL 和 SQLGlot 版本。源 SQL 的合法性可通过源数据库确认。
+- `UnsupportedError`:保存源 SQL 和完整错误信息,检查相关转换规则及目标版本的支持情况。
+- Doris 执行失败:检查生成 SQL 中的函数、数据类型、语法及数据库环境。未知函数可能被原样保留,需要确认目标端是否支持。
+- 查询结果不一致:检查两端数据、返回类型、NULL、精度、时区及排序设置。
+
+`unsupported_level=RAISE` 仅对转换器已识别的不支持情况抛出异常,生成结果仍需在 Doris 中验证。`transpile()` 不会查询数据库表结构;涉及类型判断的转换可能需要补充 Schema 或执行类型推断。详见 [SQLGlot 关于转换限制的说明](https://github.com/tobymao/sqlglot#unsupported-errors)。
+
+迁移前,请在相同逻辑数据和固定的 Session 设置下,分别执行源 SQL 和生成 SQL,校验字段类型、行值、NULL、重复行及最终排序。对于 Decimal、浮点数、日期时间、数组和 JSON 等类型,还应验证边界值。
+
+数据导入和持续同步的配置请参考 [Doris 迁移概览](../../migration/overview.md)。
+
+## 开发 HTTP 转换服务并接入 Doris
+
+### 集成原理与职责
+
+将 SQLGlot 封装为 HTTP 服务后,可供其他应用调用,也可接入 Doris 的方言转换入口。两种调用流程如下:
+
+```text
+独立转换:
+调用方 → HTTP 服务 → SQLGlot → 返回 Doris SQL 文本
+
+Doris 集成:
+客户端通过 MySQL 协议向 Doris 提交源方言 SQL
+ → FE 根据 sql_dialect 选择转换入口
+ → FE 向 sql_converter_service_url 发送 HTTP POST
+ → 用户开发的服务调用 SQLGlot,返回 Doris SQL 文本
+ → FE 解析、规划,Doris 执行转换后的 SQL
+ → 客户端收到查询结果
+```
+
+HTTP 服务接收 SQL 文本并返回转换结果,无需配置数据库连接。涉及表的查询执行前,请先完成数据迁移或配置外部 Catalog,确保 Doris 可以访问相应库表。
+
+以下示例仅接受单条查询,不支持 DDL、DML、EXPLAIN、多语句脚本和客户端命令。如需扩展语句范围,请增加相应的校验、转换规则和测试。
+
+### Doris 接口约定
+
+服务的接口需与所部署 Doris 版本保持一致。请求格式和插件配置可参考以下源码:
+
+- [HttpDialectUtils.java](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectUtils.java):实际 HTTP 请求、响应及失败处理。
+- [HttpDialectConverterPlugin.java](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectConverterPlugin.java):服务地址读取及可接受的源方言。
+
+本示例使用 `v1` 协议,接口路径为 `/api/v1/convert`。FE 通过 HTTP POST 发送请求,`Content-Type` 为 `application/json`,请求体如下:
+
+```json
+{
+ "version": "v1",
+ "sql_query": "SELECT 'hello'::TEXT AS message",
+ "from": "postgres",
+ "to": "doris",
+ "source": "text",
+ "case_sensitive": "0",
+ "enable_sql_convertor_features": [],
+ "config": "{}"
+}
+```
+
+`sql_query` 为待转换的 SQL。`from` 和 `to` 分别对应 SQLGlot 的 `read` 和 `write` 参数。其他字段由 HTTP 服务按接口约定处理。
+
+转换成功时,返回 HTTP 200,响应体如下:
+
+```json
+{
+ "version": "v1",
+ "data": "SELECT CAST('hello' AS STRING) AS message",
+ "code": 0,
+ "message": "Success"
+}
+```
+
+`data` 为转换后的 SQL 字符串,`code=0` 表示转换成功。转换失败时,返回非零 `code`,并在 `message` 中说明原因。例如,提交两条 SELECT 会返回以下响应:
+
+```json
+{
+ "version": "v1",
+ "data": "",
+ "code": 1,
+ "message": "ValueError: Exactly one query is required"
+}
+```
+
+请求参数或 JSON 格式校验失败时,FastAPI 返回 HTTP 422。
+
+### 最小示例代码
+
+本节使用 FastAPI、Pydantic 2 和 Uvicorn 实现一个基本转换接口。示例用于本地开发和联调;生产部署所需的访问控制、资源限制和监控配置见本节末尾。
+
+进入前面创建的 `sqlglot-doris-demo` 目录,激活虚拟环境并安装依赖:
+
+```bash
+source .venv/bin/activate
+python -m pip install "fastapi>=0.115,<1" "pydantic>=2,<3" "uvicorn>=0.30,<1"
+```
+
+沿用前文安装的 SQLGlot 版本。完成验证后,可执行 `python -m pip freeze > requirements.txt` 保存依赖版本。
+
+创建 `converter_server.py`,写入以下代码:
+
+```python
+import json
+from typing import Literal
+
+import sqlglot
+from fastapi import FastAPI
+from pydantic import BaseModel, ConfigDict, Field
+from sqlglot import exp
+from sqlglot.errors import ErrorLevel, SqlglotError
+
+app = FastAPI(title="SQL conversion example")
+READ_DIALECTS = {"postgres", "clickhouse", "hive", "spark", "bigquery", "snowflake"}
+
+
+class ConvertRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ version: Literal["v1"] = "v1"
+ sql_query: str = Field(min_length=1, max_length=100_000)
+ source_dialect: str = Field(alias="from")
+ target_dialect: Literal["doris"] = Field(default="doris", alias="to")
+ source: Literal["text"] = "text"
+ case_sensitive: Literal["0"] = "0"
+ enable_sql_convertor_features: list[str] = Field(default_factory=list)
+ config: str | None = None
+
+
+def convert_one(sql: str, read: str) -> str:
+ if read not in READ_DIALECTS:
+ raise ValueError(f"Unsupported source dialect: {read}")
+ statements = sqlglot.parse(sql, read=read, error_level=ErrorLevel.RAISE)
+ trees = [tree for tree in statements if tree is not None]
+ if len(trees) != 1:
+ raise ValueError("Exactly one query is required")
+ tree = trees[0]
+ excluded = (exp.DDL, exp.DML, exp.Command, exp.Into, exp.Lock)
+ if not isinstance(tree, exp.Query) or any(isinstance(node, excluded) for node in tree.walk()):
+ raise ValueError("Only a single query without DDL/DML, INTO or locking is supported")
+ return tree.sql(dialect="doris", unsupported_level=ErrorLevel.RAISE)
+
+
+def response(data: str = "", code: int = 0, message: str = "Success") -> dict:
+ return {"version": "v1", "data": data, "code": code, "message": message}
+
+
+@app.get("/healthz")
+def health() -> dict:
+ return {"status": "ok", "sqlglot_version": sqlglot.__version__}
+
+
+@app.post("/api/v1/convert")
+def convert(request: ConvertRequest) -> dict:
+ try:
+ enabled = [item for item in request.enable_sql_convertor_features if item.strip()]
+ config = json.loads(request.config) if request.config else {}
+ if enabled or config != {}:
+ raise ValueError("This example does not implement converter features or config")
+ return response(data=convert_one(request.sql_query, request.source_dialect))
+ except (SqlglotError, ValueError) as exc:
+ return response(code=1, message=f"{type(exc).__name__}: {exc}")
+ except Exception:
+ return response(code=1, message="Internal conversion error")
+```
+
+示例说明:
+
+- 每个请求独立完成解析和生成,结果通过响应返回。服务无需数据库驱动或数据库账户。
+- `case_sensitive` 仅接受 `"0"`,标识符处理使用 SQLGlot 默认方言规则。如需其他大小写处理方式,请增加对应实现和测试。
+- `enable_sql_convertor_features` 仅接受空列表或空字符串列表项;`config` 接受空对象字符串 `"{}"`、null、空字符串或省略。非空配置及未知字段会被拒绝。
+- 语句检查用于限制输入范围。SELECT 中的 UDF 仍可能产生副作用,请在 Doris 中配置所需权限。
+- `sql_query` 长度上限为 100,000 个字符。请求体字节数、CPU、内存和转换超时需另外限制。
+
+### 启动和独立接口验证
+
+在 `converter_server.py` 所在目录启动服务:
+
+```bash
+python -m uvicorn converter_server:app --host 127.0.0.1 --port 5001
+```
+
+服务以前台进程运行,按 `Ctrl+C` 停止。监听地址 `127.0.0.1` 仅允许同一主机网络环境中的客户端访问。
+
+在另一个终端检查健康状态:
+
+```bash
+curl --fail-with-body http://127.0.0.1:5001/healthz
+```
+
+发送转换请求:
+
+```bash
+curl --fail-with-body http://127.0.0.1:5001/api/v1/convert \
+ -H 'Content-Type: application/json' \
+ --data-binary @- <<'JSON'
+{
+ "version": "v1",
+ "sql_query": "SELECT 'hello'::TEXT AS message",
+ "from": "postgres",
+ "to": "doris",
+ "source": "text",
+ "case_sensitive": "0",
+ "enable_sql_convertor_features": [],
+ "config": "{}"
+}
+JSON
+```
+
+成功时返回前述 JSON 响应,`data` 中包含生成的 Doris SQL。该步骤可独立验证转换接口。`curl --fail-with-body` 用于检查 HTTP 错误,转换状态还需通过响应中的 `code` 判断。
+
+直接调用接口可使用示例白名单中的六种源方言。通过 Doris 调用时,还需符合内置 HTTP 插件的方言限制,详见下一节。
+
+### 配置 Doris 并联调
+
+在 Doris 中执行以下命令,检查相关变量:
+
+```sql
+SHOW GLOBAL VARIABLES LIKE 'sql_converter_service_url';
+SHOW VARIABLES LIKE 'sql_dialect';
+```
+
+变量说明:
+
+- `sql_converter_service_url`:全局变量,指定 FE 调用的转换服务地址。配置前请先启动转换服务。
+- `sql_dialect`:会话变量,指定当前连接提交的 SQL 方言。
+
+使用具备相应权限的账户配置服务地址。以下示例适用于服务和 FE 处于同一主机网络环境的部署:
+
+```sql
+SET GLOBAL sql_converter_service_url = 'http://127.0.0.1:5001/api/v1/convert';
+```
+
+跨主机或容器部署时,请使用 FE 可访问的主机名或网络地址,并配置服务监听地址和防火墙。Docker 容器中的 `127.0.0.1` 指向容器自身;访问宿主机服务时需配置对应的网络地址。示例接口未配置鉴权,请限制在受控网络中访问。
+
+使用 MySQL 客户端连接 Doris FE 的查询端口:
+
+```bash
+mysql -h -P -u -p
+```
+
+将 ``、`` 和 `` 替换为实际配置,查询端口默认为 9030。在同一连接中设置方言并执行查询:
+
+```sql
+SET sql_dialect = 'postgres';
+SELECT 'hello'::TEXT AS message;
+SET sql_dialect = 'doris';
+```
+
+执行成功后,Doris 返回一行数据,`message` 的值为 `hello`。该示例使用常量查询,可用于验证 FE 调用转换服务及执行生成 SQL 的完整流程。业务查询还需按实际库表和数据进行验证。
+
+本示例服务会拒绝 SET 等非查询语句。Doris 的 HTTP 转换实现可能回退到原语句,并按原生语法处理。切换方言和恢复会话前,请在部署版本中确认该行为。
+
+所引用版本的 Doris 内置 HTTP 插件接受 `presto`、`trino`、`hive`、`spark`、`postgres`、`clickhouse` 和 `starrocks`,尚未列出 BigQuery、Snowflake。本示例服务与该插件共同支持的源方言为 PostgreSQL、ClickHouse、Hive 和 Spark。接收 Presto、Trino 或 StarRocks 请求前,请扩展示例中的 `READ_DIALECTS` 并补充测试。插件的实际方言列表以所部署版本为准。
+
+测试结束后,将会话方言恢复为 `doris`。如需撤销服务地址配置,请由管理员恢复测试前的全局变量值。
+
+### 失败回退与生产实现注意事项
+
+注意:所引用版本的 `HttpDialectUtils` 在 HTTP 请求失败、响应 `code` 非零、协议版本不匹配或请求异常时,会记录日志并返回原 SQL。Doris 随后可能继续按原生语法解析。客户端收到的错误可能来自后续解析阶段,排查时请同时检查服务响应和 FE 日志。
+
+使用该回退机制时,请注意:
+
+- `unsupported_level=RAISE` 仅控制服务内部的转换错误处理。数据库读写权限仍需在 Doris 中配置。
+- 原 SQL 兼容 Doris 时,回退后仍可能执行成功。联调时请使用上述带 `::TEXT` 的示例,并检查服务是否实际收到请求。
+- 业务要求转换失败后中止执行时,需在调用方、代理或 Doris 集成层增加相应控制。
+
+生产部署前,请补充以下配置和验证:
+
+1. **兼容性测试**:固定 SQLGlot 和 Doris 版本,覆盖正常输入、NULL、非法输入、空输入、多语句、DDL/DML、未实现参数及并发请求,并校验本地 API 与 HTTP 接口的输出一致性。
+2. **资源与可用性控制**:设置请求体大小、复杂度、并发数和排队时间限制。需要中止超时转换时,应实现可终止的工作进程;线程等待超时后,转换任务可能仍在运行。
+3. **FE 请求行为**:所引用版本的 HTTP 工具未显式配置连接和读取超时,同步请求可能延长查询响应时间。请按实际版本验证网络超时、连接失败及服务不可用时的行为。
+4. **访问控制与传输安全**:限制访问来源,按需配置网关和 TLS。启用接口鉴权前,请确认 FE 客户端能够提供所需认证信息;现有请求实现未设置自定义鉴权头。
+5. **日志与监控**:记录请求标识、版本、耗时、成功率和错误类型。SQL 文本及异常信息可能包含敏感数据,请按数据安全要求配置脱敏和日志访问权限。
+
+上述生产能力需在示例基础上自行实现。转换范围由 SQLGlot 规则和 Doris 版本共同决定,HTTP 接入后仍需验证业务查询的兼容性。
+
+## 参考资料
+
+- [SQLGlot 官方仓库及安装说明](https://github.com/tobymao/sqlglot#install)
+- [SQLGlot Python API 文档](https://sqlglot.com/sqlglot.html)
+- [SQLGlot PyPI 发布包](https://pypi.org/project/sqlglot/)
+- [SQLGlot 命令行实现](https://github.com/tobymao/sqlglot/blob/main/sqlglot/__main__.py)
+- [SQLGlot 支持的方言](https://github.com/tobymao/sqlglot#supported-dialects)
+- [Doris HTTP 转换协议及错误回退实现](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectUtils.java)
+- [Doris HTTP 转换插件](https://github.com/apache/doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/plugin/dialect/HttpDialectConverterPlugin.java)
+- [Doris 全局变量定义](https://github.com/apache/doris/blob/master/fe/fe-common/src/main/java/org/apache/doris/qe/GlobalVariable.java)
+- [FastAPI 入门](https://fastapi.tiangolo.com/tutorial/first-steps/)
+- [Pydantic 字段与别名](https://docs.pydantic.dev/latest/concepts/fields/)
diff --git a/sidebars.ts b/sidebars.ts
index 31e150178356c3..ae152b9f6cea4c 100644
--- a/sidebars.ts
+++ b/sidebars.ts
@@ -215,6 +215,7 @@ const sidebars: SidebarsConfig = {
'connection-integration/data-integration/seatunnel',
'connection-integration/data-integration/smartbi',
'connection-integration/data-integration/spark-doris-connector',
+ 'connection-integration/data-integration/sqlglot',
'connection-integration/data-integration/superset',
'connection-integration/data-integration/tableau',
'connection-integration/data-integration/vector'
diff --git a/static/images/next/connection-integration/data-integration/logos/sqlglot.png b/static/images/next/connection-integration/data-integration/logos/sqlglot.png
new file mode 100644
index 00000000000000..63b11bfe0dc088
Binary files /dev/null and b/static/images/next/connection-integration/data-integration/logos/sqlglot.png differ