> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql.md).

# Text to SQL

Text to SQL 技術規格：支援的資料庫與連線字串格式、唯讀保護、網路與帳號需求、大型 schema 的處理方式與查詢結果上限。

Text to SQL 讓 Agent 把使用者的自然語言問題轉成 SQL，查詢連線的資料庫，再依查詢結果回答。本頁是給資料庫管理者與技術人員的規格說明；建立資料庫連線、關聯 Agent 的操作步驟，見使用者手冊的 [Text to SQL 功能](https://docs.maiagent.ai/build/database/text2sql) 與 [建立與設定資料庫](https://docs.maiagent.ai/build/database/create-database)。

<figure><img src="https://527168072-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F38pkhhqHl1oA6yyE9R2n%2Fuploads%2Fgit-blob-f46f2be96823acc4e50dd7fb47ed120788db81c8%2Fimage%20(30).png?alt=media" alt=""><figcaption></figcaption></figure>

## 運作方式 <a href="#how-it-works" id="how-it-works"></a>

Text to SQL 只在 Agent 使用 **Agent 模式** 時啟用。Agent 會依需要逐步呼叫下列工具：

1. 列出可查詢的資料庫（一個 Agent 可以關聯多個資料庫）。
2. 列出資料庫中可查詢的資料表與檢視表，以及您填寫的資料表說明。
3. 讀取特定資料表的欄位結構與欄位說明。
4. 執行 SQL 查詢，取得結果後作答。

每次查詢最多回傳平台設定的列數（預設 1,000 列）。超過時只回傳前面的列，並告知模型結果已截斷。連線中斷等暫時性錯誤會自動重試；SQL 語法或權限錯誤則直接把錯誤訊息交給模型，由模型修正查詢。

## 支援的資料庫 <a href="#supported-databases" id="supported-databases"></a>

| 類型                   | 連線字串格式                                                                                                       | 說明                                                                                                                     |
| -------------------- | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| MaiAgent 資料庫         | 不需要                                                                                                          | 上傳試算表等檔案建立資料表，由平台代管，見使用者手冊的 [MaiAgent 資料庫進行 Text to SQL](https://docs.maiagent.ai/build/database/text-to-sql-maiagent) |
| PostgreSQL           | `postgresql://帳號:密碼@主機:連接埠/資料庫`                                                                              | 也接受 `postgres://` 開頭                                                                                                   |
| MySQL                | `mysql+pymysql://帳號:密碼@主機:連接埠/資料庫`                                                                           |                                                                                                                        |
| Microsoft SQL Server | `mssql+pyodbc://帳號:密碼@主機:連接埠/資料庫?driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes&Encrypt=no` | 平台內建 ODBC Driver 18 for SQL Server                                                                                     |
| Oracle               | `oracle+oracledb://帳號:密碼@主機:連接埠/?service_name=服務名稱`                                                          | 支援 Oracle Database 12.1 以上；11g 需要平台額外啟用 Oracle Client，請洽 MaiAgent 窗口                                                   |
| SynxDB               | `postgresql://帳號:密碼@主機:連接埠/資料庫`                                                                              | PostgreSQL 相容的 MPP 資料倉儲                                                                                                |

連線字串的開頭必須和所選類型一致，否則無法儲存。建立時可以先按 <mark style="color:blue;">測試連線</mark> 確認平台連得到資料庫。

## 連線安全 <a href="#connection-security" id="connection-security"></a>

### 唯讀保護 <a href="#read-only" id="read-only"></a>

平台在兩個層次限制查詢只能讀取：

* **語法檢查**：只允許 `SELECT`（含 `WITH`、`UNION` 等讀取語法）。`INSERT`、`UPDATE`、`DELETE`、`MERGE`、`CREATE`、`ALTER`、`DROP`、`TRUNCATE`、`SELECT … INTO`，以及用分號串接的多個陳述式，都會被擋下。
* **唯讀交易**：PostgreSQL、MySQL 與 Oracle 的查詢在唯讀交易中執行，資料庫本身會拒絕寫入。SQL Server 沒有對應的唯讀工作階段設定，平台改以「查詢後一律回復（rollback）、從不提交」處理，保護程度較弱。

{% hint style="warning" %}
**請一律使用唯讀帳號連線。** 平台的保護是第二道防線；資料庫帳號只授予需要的資料表或檢視表的讀取權限，才是最直接的控管，對 SQL Server 尤其重要。
{% endhint %}

### 帳號與連線字串 <a href="#credentials" id="credentials"></a>

* 建議為 MaiAgent 建立專用帳號，只授予需要查詢的資料表或檢視表的 `SELECT` 權限。
* 連線字串含帳號密碼，寫入後讀取時只會顯示遮罩後的內容；要更換時重新輸入完整的連線字串。
* 誰能把資料庫關聯到 Agent、哪些角色能使用，依資料庫的角色權限設定，見 [建立與設定資料庫](https://docs.maiagent.ai/build/database/create-database)。

### 網路需求 <a href="#network" id="network"></a>

* 資料庫必須能從 MaiAgent 平台連線到：連線方向是平台主動連到資料庫的主機與連接埠（即連線字串中的位址）。按 <mark style="color:blue;">測試連線</mark> 時與每次查詢時都會建立連線。
* 連接埠以連線字串為準，各資料庫的預設值為 PostgreSQL 5432、MySQL 3306、SQL Server 1433、Oracle 1521、SynxDB 5432（依部署設定）。
* **SaaS**：資料庫需開放給 MaiAgent 平台的對外連線位址。要設定防火牆白名單時，請洽 MaiAgent 窗口取得對外 IP。
* **地端與私有雲**：平台與資料庫需在同一網段，或透過 VPN 等方式互通。

## 大型 schema 的處理 <a href="#large-schemas" id="large-schemas"></a>

平台不會把整個 schema 一次送進模型：模型先拿到資料表清單與說明，需要時才讀取個別資料表的欄位結構。資料表很多時，建議：

* **用&#x20;**<mark style="color:blue;">**指定資料表**</mark>**&#x20;縮小範圍**：只開放回答問題需要的資料表。留空時，可查詢預設 schema 下的所有資料表與檢視表。
* **其他 schema 的資料表要寫出 schema 名稱**：例如 `sales.orders`。平台只掃描預設 schema，以及指定資料表中出現的 schema。
* **填寫&#x20;**<mark style="color:blue;">**資料表結構描述**</mark>：說明資料表的用途與欄位意義，模型越能選對資料表與欄位。
* **先建好檢視表**：把常用的關聯（JOIN）與商業邏輯包成檢視表，再只開放檢視表，可以同時降低查詢錯誤與權限風險。

## 常見問題 <a href="#faq" id="faq"></a>

<details>

<summary>測試連線失敗？</summary>

依序確認：連線字串的開頭與所選類型一致、主機與連接埠正確、資料庫允許 MaiAgent 平台的連線位址（SaaS 請洽窗口取得對外 IP）、帳號密碼正確。Oracle 11g 需要平台額外設定，請洽 MaiAgent 窗口。

</details>

<details>

<summary>怎麼用 API 取得某張資料表的筆數？</summary>

資料庫 API（`/api/v1/sql-databases/…`）只提供連線、資料表與欄位的設定管理；資料表清單回應裡的 `count` 是分頁的資料表數量，不是資料列數，也沒有回傳列數或執行 SQL 的端點。要知道筆數，請在對話中問 Agent（例如「orders 資料表有幾筆？」），模型會產生 `SELECT COUNT(*)` 查詢並回答；或直接連線您的資料庫查詢。

</details>

<details>

<summary>Agent 可以透過 Text to SQL 修改資料嗎？</summary>

不行。平台只允許讀取類的查詢，寫入與結構變更的語法都會被擋下。API 文件中資料庫、資料表與欄位的 `POST`／`PUT`／`PATCH` 端點管理的是連線設定、資料表說明與欄位描述，以及把試算表上傳成資料表；它們不會寫入或修改既有資料表裡的資料列，對話中的 Agent 也不能呼叫這些端點。

</details>

<details>

<summary>查詢元資料（Query Metadata）會限制 Text to SQL 嗎？</summary>

不會。查詢元資料只套用在知識庫檢索，Agent 產生與執行 SQL 時不會參考它，也沒有逐次請求限制資料表或資料列的欄位。能縮小資料庫範圍的只有：資料庫是否啟用、是否關聯到這個 Agent、<mark style="color:blue;">指定資料表</mark>，以及資料庫帳號本身的權限（含檢視表）。要讓不同身分查到不同資料，請用不同的 Agent 搭配不同的連線或唯讀帳號。

</details>

<details>

<summary>Agent 的設定頁看不到資料庫設定？</summary>

資料庫設定只在 Agent 模式下可用。請先在 Agent 的回覆模式設定中選擇 Agent 模式。

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
