table_data_preview.go 2.6 KB
package bytelib

import (
	"context"
	"net/http"
)

func (gateway *ByteMetadataService) TableDataPreview(ctx context.Context, request *TableDataPreviewRequest) (TablePreviewResponse, error) {
	var result TablePreviewResponse
	if err := gateway.Do(ctx, "/data/table-preview", http.MethodPost, request, &result); err != nil {
		return result, err
	}
	return result, nil
}

func (gateway *ByteMetadataService) FastTableData(ctx context.Context, objectId int64, limit int) (TablePreviewResponse, error) {
	return gateway.TableDataPreview(ctx, &TableDataPreviewRequest{
		ObjectType: ObjectMetaTable,
		ObjectId:   objectId,
		Where: &TableQueryWhere{
			PageNumber: 0,
			PageSize:   limit,
		},
	})
}

type TableDataPreviewRequest struct {
	Token      string           `header:"x-mmm-accesstoken"`
	ObjectId   int64            `json:"objectId"`   //表ID
	ObjectType string           `json:"objectType"` //表类型 File:文件 MetaTable:元表 DBTable:数据库表 ;当对象类型为DBTable时 objectId 1:表操作日志 2.拆解模块日志
	Where      *TableQueryWhere `json:"where"`      //查询条件
	UseCache   bool             `json:"useCache"`
	HiddenData bool             `json:"hiddenData"` // 隐藏数据,只返回结构
}

type TableQueryWhere struct {
	PageNumber int                    `json:"pageNumber"`
	PageSize   int                    `json:"pageSize"`
	Conditions []*TableQueryCondition `json:"conditions"`
}

func (w *TableQueryWhere) WithPageSize(page, size int) *TableQueryWhere {
	w.PageNumber = page - 1
	w.PageSize = size
	if page == 0 {
		w.PageNumber = 0
	}
	if w.PageSize == 0 {
		w.PageSize = 20
	}
	return w
}

type TableQueryCondition struct {
	Field *Field   `json:"field"` //字段
	Like  string   `json:"like"`  //模糊匹配
	In    []string `json:"in"`    //包含项
	Ex    []string `json:"ex"`    //排除项
	Order string   `json:"order"` //排序 ASC正序 DESC降序
}

type TablePreviewResponse TableData

type TablePreview struct {
	Code int        `json:"code"`
	Msg  string     `json:"msg"`
	Data *TableData `json:"data"`
}

type TableData struct {
	//表ID
	ObjectId int64 `json:"objectId"`
	//表名
	Name string `json:"name"`
	//数据
	Grid *TableDataGrid `json:"grid,optional"`
	//字段
	Fields []*Field `json:"fields"`
}

type TableDataGrid struct {
	//数据列表
	List []map[string]string `json:"list"`
	//总记录数
	Total int64 `json:"total"`
}

func (t TablePreviewResponse) FirstCellData() string {
	var column string
	if len(t.Fields) >= 1 {
		column = t.Fields[0].SQLName
	}
	if len(t.Fields) >= 2 && t.Fields[0].SQLName == "id" {
		column = t.Fields[1].SQLName
	}
	if len(t.Grid.List) > 0 {
		return t.Grid.List[0][column]
	}
	return ""
}