golang实现原始数据库过滤语法

golang gin 数据库过滤语法

func (s APIGetAlarmListsInputs) collectFilters() string {
    tmp := []string{}
    if s.StartTime != 0 {
        tmp = append(tmp, fmt.Sprintf("timestamp >= FROM_UNIXTIME(%v)", s.StartTime))
    }
    if s.EndTime != 0 {
        tmp = append(tmp, fmt.Sprintf("timestamp <= FROM_UNIXTIME(%v)", s.EndTime))
    }
    if s.Priority != -1 {
        tmp = append(tmp, fmt.Sprintf("priority = %d", s.Priority))
    }
    if s.Status != "" {
        status := ""
        statusTmp := strings.Split(s.Status, ",")
        for indx, n := range statusTmp {
            if indx == 0 {
                status = fmt.Sprintf(" status = '%s' ", n)
            } else {
                status = fmt.Sprintf(" %s OR status = '%s' ", status, n)
            }
        }
        status = fmt.Sprintf("( %s )", status)
        tmp = append(tmp, status)
    }
    if s.ProcessStatus != "" {
        pstatus := ""
        pstatusTmp := strings.Split(s.ProcessStatus, ",")
        for indx, n := range pstatusTmp {
            if indx == 0 {
                pstatus = fmt.Sprintf(" process_status = '%s' ", n)
            } else {
                pstatus = fmt.Sprintf(" %s OR process_status = '%s' ", pstatus, n)
            }
        }
        pstatus = fmt.Sprintf("( %s )", pstatus)
        tmp = append(tmp, pstatus)
    }
    if s.Metrics != "" {
        tmp = append(tmp, fmt.Sprintf("metrics regexp '%s'", s.Metrics))
    }
    if s.EventId != "" {
        tmp = append(tmp, fmt.Sprintf("id = '%s'", s.EventId))
    }
    if s.Endpoints != "" {
        tmp = append(tmp, fmt.Sprintf("endpoint = '%s'", s.Endpoints))
    }
    if s.StrategyId != 0 {
        tmp = append(tmp, fmt.Sprintf("strategy_id = %d", s.StrategyId))
    }
    if s.TemplateId != 0 {
        tmp = append(tmp, fmt.Sprintf("template_id = %d", s.TemplateId))
    }

    filterStrTmp := strings.Join(tmp, " AND ")
    if filterStrTmp != "" {
        filterStrTmp = fmt.Sprintf("WHERE %s", filterStrTmp)
    }
    return filterStrTmp
}

你可能感兴趣的:(golang实现原始数据库过滤语法)