Exemple #1
0
func NewBeforeCursor(tableName string, c decode.Criteria) func(decode.Filter) (string, string, []interface{}) {
	idCursor := func(filter decode.Filter) (string, string, []interface{}) {
		operator := "<"
		sorter := c.Sorters[0]
		column := translation.FieldToColumn(sorter.Field)

		if sorter.Direction == "DESC" {
			operator = ">"
		}

		where, args := NewWhereCursor(tableName, column, operator, filter)
		return "", where, args
	}

	return idCursor
}
Exemple #2
0
func (b Builder) Select(o SelectOpts) (string, []interface{}) {
	selectColumns := fmt.Sprintf("%s.*", o.Table)
	if len(o.Columns) > 0 {
		selectColumns = strings.Join(o.Columns, ", ")
	}
	q := fmt.Sprintf("SELECT %s FROM %s", selectColumns, o.Table)
	var args []interface{}
	var strs []string
	binds := o.Binds

	var innerJoin []string
	var where []string
	for _, filter := range o.C.Filters {
		if f, ok := o.Builders[filter.Field]; ok {
			j, w, a := f(filter)

			if j != "" {
				innerJoin = append(innerJoin, j)
			}

			if w != "" {
				where = append(where, w)
			}

			if len(a) > 0 {
				args = append(args, a...)
			}
		} else {
			column := translation.FieldToColumn(filter.Field)

			if filter.Operator == "=" {
				strs = strings.Split(filter.Value, ",")
				var inStr []string
				for _, str := range strs {
					args = append(args, str)
					bindStr := "?"

					if bindVal, ok := binds[column]; ok {
						bindStr = bindVal
					}
					inStr = append(inStr, bindStr)
				}

				bQ := fmt.Sprintf("%s.%s IN (%s)", o.Table, column, strings.Join(inStr, ","))
				where = append(where, bQ)
			} else {
				// comparison operator present
				bindStr := "?"

				if bindVal, ok := binds[column]; ok {
					bindStr = bindVal
				}
				compQ := fmt.Sprintf("%s.%s %s %s", o.Table, column, filter.Operator, bindStr)

				args = append(args, filter.Value)
				where = append(where, compQ)
			}
		}
	}

	if len(innerJoin) > 0 {
		q += ` INNER JOIN `
		q += strings.Join(innerJoin, " INNER JOIN ")
	}

	if len(where) > 0 {
		q += ` WHERE `
		q += strings.Join(where, " AND ")
	}

	if lenSorters := len(o.C.Sorters); lenSorters > 0 {
		q += ` ORDER BY `
		for i, sorter := range o.C.Sorters {
			fieldName := translation.FieldToColumn(sorter.Field)
			q += fieldName + ` ` + sorter.Direction

			if i+1 != lenSorters {
				q += ","
			}
		}
	} else if o.DefaultOrder != "" {
		q += fmt.Sprintf(" ORDER BY %s", o.DefaultOrder)
	}

	if o.C.Limit > 0 {
		q += ` LIMIT ` + strconv.Itoa(o.C.Limit)
	} else if o.DefaultLimit > 0 {
		q += fmt.Sprintf(" LIMIT %v", o.DefaultLimit)
	}

	if o.C.Offset > 0 {
		q += ` OFFSET ` + strconv.Itoa(o.C.Offset)
	}

	q = o.Db.Rebind(q)
	fmt.Println(q)

	return q, args
}