# 設定

本頁列出 `init()` 接受的所有設定來源、欄位與預設值。

## 設定來源優先序

`init(config?)` 依下表為讀寫兩側各選一個來源（`src/MySQLPool.ts:52-72`），選定後整組使用，不會跨來源合併欄位：

| 連線池 | 來源（由高到低） |
|---|---|
| 讀取 | `config.config` → `config.read` → `DB_READ_*` 環境變數 |
| 寫入 | `config.config` → `config.write` → `config.read` → `DB_WRITE_*` 環境變數 |

```typescript
import MySQLPool from "@pardnchiu/mysql-pool";

// 讀寫分離
await MySQLPool.init({
  read: { host: "replica.local", user: "reader", password: "secret", database: "app", connectionLimit: 16 },
  write: { host: "primary.local", user: "writer", password: "secret", database: "app", connectionLimit: 4 },
});
```

## `MySQLConfig`

```typescript
interface MySQLConfig {
  host?: string;
  port?: number;
  user?: string;
  password?: string;
  database?: string;
  charset?: string;
  connectionLimit?: number;
}
```

所有欄位經 `correctConfig()` 補預設值並 `trim()`（`src/MySQLPool.ts:40-50`）：

| 欄位 | 預設值 | 說明 |
|---|---|---|
| `host` | `localhost` | |
| `port` | `3306` | 無法解析為整數時同樣回到 `3306` |
| `user` | `root` | |
| `password` | `""` | 前後空白會被去除 |
| `database` | `""` | 空字串時不建立該側連線池 |
| `charset` | `utf8mb4` | |
| `connectionLimit` | `8` | 連線池同時開啟的連線上限 |

`MySQLConfig` 未從套件匯出。

## 環境變數

未傳入對應設定物件時讀取下列變數：

| 讀取端 | 寫入端 | 預設值 |
|---|---|---|
| `DB_READ_HOST` | `DB_WRITE_HOST` | `localhost` |
| `DB_READ_PORT` | `DB_WRITE_PORT` | `3306` |
| `DB_READ_USER` | `DB_WRITE_USER` | `root` |
| `DB_READ_PASSWORD` | `DB_WRITE_PASSWORD` | `""` |
| `DB_READ_DATABASE` | `DB_WRITE_DATABASE` | `""`（不建立連線池） |
| `DB_READ_CHARSET` | `DB_WRITE_CHARSET` | `utf8mb4` |
| `DB_READ_CONNECTION` | `DB_WRITE_CONNECTION` | `4` |

注意連線數預設值的差異：走環境變數時為 `4`，走設定物件且未指定 `connectionLimit` 時為 `8`。

## 相關頁面

- [讀寫連線池](/zh/read-write-pools)
- [生命週期與關閉](/zh/shutdown)
