# MySQL TaskStore node_executions 第一版實作紀錄

## 1. 實作目的

本次實作將 `TaskExecutionRecord.NodeRecords` 從記憶體任務紀錄延伸到 MySQL TaskStore 的內部儲存流程，讓每次 `Save(record)` 在有節點紀錄時，可同步產生 `node_executions` 寫入命令。

本批仍屬第二階段 PoC 收斂，目標是完成 fake gateway 與 SQL 組裝驗證，不執行真實 DB DDL、不變更 `ITaskStore` public contract，也不把 ConsoleHost / ServiceHost 納入啟動流程。

## 2. 完成內容

| 項目 | 狀態 | 說明 |
| --- | --- | --- |
| `node_executions` schema class | 已完成 | 新增 `MySqlTaskNodeExecutionSchema`，用 C# Attribute 維護 table、欄位、索引與 comment。 |
| SQL builder | 已完成 | 新增刪除指定 task 節點紀錄與插入單筆節點紀錄 SQL。 |
| Save 流程 | 已完成 | `MySqlTaskStore.Save` 會先 upsert `task_executions`，再於有 `NodeRecords` 時刪除舊節點並依序插入新節點。 |
| batch gateway | 已完成 | `IMySqlTaskStoreGateway` 新增 internal batch non-query，正式 gateway 以單一 transaction 執行同批命令。 |
| fake gateway 測試 | 已完成 | 可驗證 task upsert、node delete、node insert 的命令順序、參數映射、長度截斷與錯誤遮蔽。 |
| schema / SQL 測試 | 已完成 | 驗證 schema parser、MySQL SQL generator、Dry Run missing table 對 `node_executions` 的支援。 |

## 3. 儲存流程

```text
MySqlTaskStore.Save(record)
  1. 驗證 MySqlTaskStoreOptions
  2. 建立 task_executions upsert command
  3. 若 record.NodeRecords 為空，只送出 task command
  4. 若 record.NodeRecords 有資料：
     - DELETE node_executions WHERE task_id = @TaskId
     - 依 NodeRecords 順序 INSERT node_executions，sequence_no 從 1 開始
  5. 透過 internal batch gateway 以 transaction 執行
```

## 4. 目前邊界

- 未執行 `CREATE TABLE` / `ALTER TABLE` / `DROP TABLE`。
- 未對真實 MySQL 寫入 `node_executions`。
- 未修改 `ITaskStore` public method。
- 未修改 `TaskExecutionRecord` / `TaskNodeExecutionRecord` public constructor 與 property。
- `FindById` / `ListRecent` 仍只還原 `task_executions` 摘要，尚未回填 `NodeRecords`。
- `command_executions`、詳細 log table、Schema Apply / DDL Executor 仍維持延後項目。

## 5. 驗證結果

執行指令：

```powershell
dotnet test tests\HS.DeviceControl.Infrastructure.MySql.Tests\HS.DeviceControl.Infrastructure.MySql.Tests.csproj
dotnet test
```

結果：

- MySQL Infrastructure 測試通過：49 passed。
- 全專案測試通過：Core、Adapters、WorkflowSimulation、ModbusPoc、Infrastructure.MySql 全部通過。
- 僅出現 .NET 5.0 已停止支援警告，屬既有技術決策，不影響本次測試結果。

## 6. 下一步建議

建議下一步做「node_executions manual-only 真實測試 DB 驗證設計」，先確認測試 DB 是否已建立 `node_executions`，再用 manual-only gate 執行寫入 / 查詢 / metadata 檢查。
