:::mermaid
flowchart TD
A["🔵 Bắt đầu: explain_query"] --> B["Phân tích tham số:<br/>sql, analyze, hypothetical_indexes"]
B --> C{"Có Hypothetical Indexes?"}
C -->|"Có"| D["Kiểm tra HypoPG Extension"]
C -->|"Không"| E["Chuẩn bị EXPLAIN Query"]
D --> F{"HypoPG khả dụng?"}
F -->|"Không"| G["Trả về lỗi:<br/>HypoPG chưa cài đặt"]
F -->|"Có"| H["Tạo Hypothetical Indexes"]
H --> H1["Với mỗi index config:"]
H1 --> H2["hypopg_create_index<br/>CREATE INDEX ON table USING method columns"]
H2 --> H3["Lưu Index OIDs"]
H3 --> I["Chuẩn bị EXPLAIN Query"]
E --> I
I --> J{"analyze = true?"}
J -->|"Có"| K["EXPLAIN ANALYZE FORMAT JSON"]
J -->|"Không"| L["EXPLAIN FORMAT JSON"]
K --> M["Thực thi EXPLAIN"]
L --> M
M --> N{"Có Hypothetical Indexes?"}
N -->|"Có"| O["Xóa Hypothetical Indexes:<br/>hypopg_drop_index"]
N -->|"Không"| P["Phân tích JSON Result"]
O --> P
P --> Q["Trích xuất Plan Details:<br/>- Node Type<br/>- Cost<br/>- Rows<br/>- Width"]
Q --> R["Định dạng Response:<br/>- Execution Plan Tree<br/>- Cost Analysis<br/>- Index Usage"]
R --> S["Trả về kết quả"]
S --> T["🔴 Kết thúc"]
G --> T
style A fill:#4CAF50,color:white
style T fill:#f44336,color:white
style C fill:#2196F3,color:white
style F fill:#FF9800,color:white
style J fill:#FF9800,color:white
style N fill:#FF9800,color:white