<span id="管理数据看板与图表"></span>

# Manage Dashboards and Charts

Create a dashboard from workspace source tables, add and run a chart query, verify the matching execution ID before reading chart results, or list and refresh existing dashboards.

(sdk-ai-studio-dashboard-flow)=
<span id="任务流程"></span>

## Task flow

Create a dashboard bound to source table IDs, add a chart, and trigger a chart run to obtain an execution ID. When reading chart results, verify that the response matches that execution ID and has reached `completed` before reading rows.

```text
Source table IDs + Verified SQL
               │
               ▼
  Create dashboard and add chart
               │
               ▼
 Run chart (obtain execution ID)
               │
               ▼
Match execution ID and read results
```

(sdk-ai-studio-dashboard-prepare)=
<span id="准备"></span>

## Prerequisites

1. Complete the endpoint, personal access token, and workspace setup in [Use the SDK](../../../quickstart/ai-studio/sdk.md).
2. **Source table IDs** (`TABLE_IDS`): obtain actual integer table IDs from [Manage Catalogs, Databases, and Tables](../资源中心/管理目录、数据库和表.md) or from the catalog database table list (separate multiple IDs with commas; source tables may span databases, and query permission is required on every table).
3. **Chart query SQL** (`DASHBOARD_SQL`): prepare valid SQL using database-qualified table names (you can test the query first in [Run SQL Queries](执行SQL查询.md)).

(sdk-ai-studio-dashboard-create)=
<span id="创建并运行图表"></span>

## Create and run a chart

Set comma-separated source table IDs and the chart SQL query. The example below creates a dashboard and a table chart, triggers a chart run, and reads the execution status and result.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os
import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"], os.environ["PRODUCT_API_KEY"]
)
service = client.dashboard(os.environ["WORKSPACE_ID"])
table_ids = [int(value) for value in os.environ["TABLE_IDS"].split(",")]
dashboard = service.create(sdk.DataDashboardMutationRequest(
    name="Sales review", sources=[sdk.DataDashboardSourceInput(table_id=value)
                                for value in table_ids],
))
sql_text = os.environ["DASHBOARD_SQL"]
chart = service.create_chart(dashboard.id, sdk.DataDashboardChartMutationRequest(
    name="Sales results", chart_type="table", sql_text=sql_text,
    chart_config="{}", layout_config="{}", refresh_interval="manual",
))
run = service.run_chart(dashboard.id, chart.id)
print("Dashboard:", dashboard.id, "Chart:", chart.id, "Execution:", run.execution_id)
result = service.chart_result(dashboard.id, chart.id)
print("Execution:", result.execution_id, "Status:", result.status, "Error:", result.error)
if (run.execution_id and result.execution_id == run.execution_id
        and result.status == "completed" and result.HasField("result")):
    print("Columns:", result.result.columns)
    for row in result.result.result:
        print(list(row))
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"os"
	"strconv"
	"strings"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		panic(err)
	}
	service := client.Dashboard(os.Getenv("WORKSPACE_ID"))
	sources := []*sdk.DataDashboardSourceInput{}
	for _, value := range strings.Split(os.Getenv("TABLE_IDS"), ",") {
		id, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
		if err != nil {
			panic(err)
		}
		sources = append(sources, &sdk.DataDashboardSourceInput{TableId: id})
	}
	dashboard, err := service.Create(ctx, &sdk.DataDashboardMutationRequest{
		Name:    "Sales review",
		Sources: sources,
	})
	if err != nil {
		panic(err)
	}
	sqlText := os.Getenv("DASHBOARD_SQL")
	chart, err := service.CreateChart(ctx, dashboard.GetId(), &sdk.DataDashboardChartMutationRequest{
		Name:            "Sales results",
		ChartType:       "table",
		SqlText:         sqlText,
		ChartConfig:     "{}",
		LayoutConfig:    "{}",
		RefreshInterval: "manual",
	})
	if err != nil {
		panic(err)
	}
	run, err := service.RunChart(ctx, dashboard.GetId(), chart.GetId())
	if err != nil {
		panic(err)
	}
	fmt.Println("Dashboard:", dashboard.GetId(), "Chart:", chart.GetId(), "Execution:", run.GetExecutionId())
	result, err := service.ChartResult(ctx, dashboard.GetId(), chart.GetId())
	if err != nil {
		panic(err)
	}
	fmt.Println("Execution:", result.GetExecutionId(), "Status:", result.GetStatus(), "Error:", result.GetError())
	if run.GetExecutionId() != "" && result.GetExecutionId() == run.GetExecutionId() &&
		result.GetStatus() == "completed" && result.GetResult() != nil {
		fmt.Println("Columns:", result.GetResult().GetColumns())
		for _, row := range result.GetResult().GetResult() {
			fmt.Println(row.AsSlice())
		}
	}
}
```

::::

:::::

Save the dashboard ID, chart ID, and execution ID. The example prints rows only when the response matches the submitted execution ID, has status `completed`, and populates `result`; on the initial read, the query may still be running or may not yet reflect the new execution, so continue polling the same dashboard and chart while verifying `execution_id`. Enforce an explicit polling deadline; if the deadline expires, retain the execution ID and inspect the existing run before starting another run.

(sdk-ai-studio-dashboard-s1)=
<span id="读取并刷新已有看板"></span>

## Read and refresh existing dashboards

When paginating dashboards in a workspace, pass `next_page_token` until `has_more` is false. After selecting a dashboard, read its detail record to inspect configured charts, or refresh the dashboard to submit runs across its charts.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
page = service.list(sdk.DataDashboardListRequest(page_size=20))
for item in page.items:
    print(item.id, item.name)

detail = service.get(dashboard.id)
print("Charts:", len(detail.charts))

refreshed = service.refresh(dashboard.id)
for chart_run in refreshed.runs:
    print(chart_run.chart_id, chart_run.execution_id, chart_run.status)
```

::::

::::{tab-item} Go
:sync: go

```go
page, err := service.List(ctx, &sdk.DataDashboardListRequest{PageSize: 20})
if err != nil {
	panic(err)
}
for _, item := range page.GetItems() {
	fmt.Println(item.GetId(), item.GetName())
}

detail, err := service.Get(ctx, dashboard.GetId())
if err != nil {
	panic(err)
}
fmt.Println("Charts:", len(detail.GetCharts()))

refreshed, err := service.Refresh(ctx, dashboard.GetId())
if err != nil {
	panic(err)
}
for _, chartRun := range refreshed.GetRuns() {
	fmt.Println(chartRun.GetChartId(), chartRun.GetExecutionId(), chartRun.GetStatus())
}
```

::::

:::::

(sdk-ai-studio-dashboard-next)=
<span id="下一步"></span>

## Next steps

- [Run SQL Queries](执行SQL查询.md)
- [Inspect SQL History and Profiles](../监测/查看SQL历史与画像.md)
