data_table.go 2.3 KB
package domain

import "strings"

type DataTable struct {
	Fields []*Field   `json:"fields"`
	Data   [][]string `json:"data"`
	Total  int64      `json:"total"`
}

type Where struct {
	PageNumber int         `json:"pageNumber"`
	PageSize   int         `json:"pageSize"`
	Conditions []Condition `json:"conditions"`
}

func (w Where) Offset() int {
	if w.PageNumber == 0 && w.PageSize == 0 {
		return 0
	}
	return (w.PageNumber - 1) * w.PageSize
}

func (w Where) ValidSql() (err error) {
	for _, c := range w.Conditions {
		if err = SqlDetections(c.Like); err != nil {
			return err
		}
		//if err = SqlDetections(c.In...); err != nil {
		//	return err
		//}
		//if err = SqlDetections(c.Ex...); err != nil {
		//	return err
		//}
		if err = SqlDetections(c.Order); err != nil {
			return err
		}
		for _, r := range c.Range {
			if err = SqlDetections(r.Val); err != nil {
				return err
			}
		}
	}
	return
}

type Condition struct {
	Field *Field        `json:"field"`
	Like  string        `json:"like"`
	In    []interface{} `json:"in"`
	Ex    []interface{} `json:"ex"`
	Range []RangStruct  `json:"range"`
	Order string        `json:"order"`
}

func (t *DataTable) OptionalValue(args ...string) []string {
	var values = make([]string, 0)
	match := ""
	filedType := ""
	if len(args) > 0 {
		match = args[0]
	}
	if len(args) > 1 {
		filedType = args[1]
	}
	if len(t.Data) > 0 && len(t.Data[0]) == 1 {
		for i := range t.Data {
			if len(t.Data[i]) == 0 {
				continue
			}
			if len(match) > 0 && !strings.Contains(t.Data[i][0], match) {
				continue
			}
			if filedType == Float.ToString() {
				values = append(values, RoundFieldValue(&Field{SQLType: filedType}, t.Data[i][0]))
				continue
			}
			values = append(values, t.Data[i][0])
		}
	}
	return values
}

func (t *DataTable) Values(f *Field) []string {
	var res = make([]string, 0)
	index := -1
	for i := range t.Fields {
		if t.Fields[i].SQLName == f.SQLName {
			index = i
			break
		}
	}
	if index < 0 {
		return res
	}
	for i := range t.Data {
		for j := range t.Data[i] {
			if j == index {
				res = append(res, RoundFieldValue(f, t.Data[i][j]))
				break
			}
		}
	}
	return res
}

func (t *DataTable) MatchFields(from []*Field) []*Field {
	return from
}

type RangStruct struct {
	Op  string      `json:"op"`
	Val interface{} `json:"val"`
}