//Generates the ORDER BY clause for an SQL statement
339473
func (me *DefaultAdapter) OrderSql(buf *SqlBuilder, order ColumnList) error {
	if order != nil && len(order.Columns()) > 0 {
		buf.Write(me.OrderByFragment)
		return me.Literal(buf, order)
	}
	return nil
}
1351921
func (q *BaseQueryBuilder) BuildOrderBy(cols []string) string {
	if len(cols) == 0 {
		return ""
	}
	s := ""
	for i, col := range cols {
		if i > 0 {
			s += ", "
		}
		matches := orderRegex.FindStringSubmatch(col)
		if len(matches) == 0 {
			s += q.db.QuoteColumnName(col)
		} else {
			col := col[:len(col)-len(matches[0])]
			dir := matches[1]
			s += q.db.QuoteColumnName(col) + " " + dir
		}
	}
	return "ORDER BY " + s
}
209133
func (query Query) Order(order ...c.Order) Query {
	query.OrderClause = append(query.OrderClause, order...)
	return query
}
842444
func (d *Dataset) sql(table, dbType string) *Exportable {
	b := newBuffer()

	tableSQL, columnTypes, columnValues := d.createTable(table, dbType)
	b.WriteString(tableSQL)

	reg, _ := regexp.Compile("[']")
	// inserts
	for i := range d.data {
		b.WriteString("INSERT INTO " + table + " VALUES(" + strconv.Itoa(i+1) + ", ")
		for j, col := range d.headers {
			asStr := d.asString(columnValues[col][i])
			if isStringColumn(columnTypes[col]) {
				b.WriteString("'" + reg.ReplaceAllString(asStr, "''") + "'")
			} else if strings.HasPrefix(columnTypes[col], "TIMESTAMP") {
				if dbType == typeMySQL {
					b.WriteString("CONVERT_TZ('" + asStr[:10] + " " + asStr[11:19] + "', '" + asStr[len(asStr)-6:] + "', 'SYSTEM')")
				} else {
					b.WriteString("'" + asStr + "'") // simpler with Postgres
				}
			} else {
				b.WriteString(asStr)
			}
			if j < len(d.headers)-1 {
				b.WriteString(", ")
			}
		}
		b.WriteString(");\n")
	}
	b.WriteString("\nCOMMIT;\n")

	return newExportable(b)
}
628547
func SelectBySql(query string, value ...interface{}) *SelectStmt {
	return &SelectStmt{
		raw: raw{
			Query: query,
			Value: value,
		},
		LimitCount:  -1,
		OffsetCount: -1,
	}
}
1064895
func (stmt SelectStmt) OrderBy(params ...Orderable) SelectStmt {
	order := make([]OrderedColumn, len(params))
	// Since columns may be given without an ordering method, perform the
	// orderable conversion whether or not it is already ordered
	for i, column := range params {
		order[i] = column.Orderable()
	}
	stmt.order = order
	return stmt
}
603159
func (q *Query) OrderExpr(order string, params ...interface{}) *Query {
	if order != "" {
		q.order = append(q.order, &queryParamsAppender{order, params})
	}
	return q
}
1217221
func (session *Session) SQL(query interface{}, args ...interface{}) *Session {
	session.statement.SQL(query, args...)
	return session
}
1001505
func (dbMan *dbManager) buildInsertSql(tableName string, orderedColumns []string, rows []common.Row) string {
	if len(rows) == 0 {
		return ""
	}
	normalizedTableName := normalizeTableName(tableName)
	var values string = ""

	var i, j int
	k := 1
	for i = 0; i < len(rows)-1; i++ {
		values += "("
		for j = 0; j < len(orderedColumns)-1; j++ {
			values += fmt.Sprintf("$%d,", k)
			k++
		}
		values += fmt.Sprintf("$%d),", k)
		k++
	}
	values += "("
	for j = 0; j < len(orderedColumns)-1; j++ {
		values += fmt.Sprintf("$%d,", k)
		k++
	}
	values += fmt.Sprintf("$%d)", k)

	sql := "INSERT INTO " + normalizedTableName
	sql += "(" + strings.Join(orderedColumns, ",") + ") "
	sql += "VALUES " + values

	return sql
}
180666
func (c *Connection) Order(stmt string) *Query {
	return Q(c).Order(stmt)
}
850749
func GenerateLimitQuery(selStmt sqlparser.SelectStatement) *sqlparser.ParsedQuery {
	buf := sqlparser.NewTrackedBuffer(nil)
	switch sel := selStmt.(type) {
	case *sqlparser.Select:
		limit := sel.Limit
		if limit == nil {
			sel.Limit = execLimit
			defer func() {
				sel.Limit = nil
			}()
		}
	case *sqlparser.Union:
		// Code is identical to *Select, but this one is a *Union.
		limit := sel.Limit
		if limit == nil {
			sel.Limit = execLimit
			defer func() {
				sel.Limit = nil
			}()
		}
	}
	buf.Myprintf("%v", selStmt)
	return buf.ParsedQuery()
}
880590
func orderByBindingsChecker() ClauseHook {
	var f ClauseHook
	f = func(s *Statement, _ Symbol) (ClauseHook, error) {
		// Force working projection flush.
		outs := make(map[string]bool)
		for _, out := range s.OutputBindings() {
			outs[out] = true
		}
		seen, dups := make(map[string]bool), false
		for _, cfg := range s.orderBy {
			// Check there are no contradictions
			if b, ok := seen[cfg.Binding]; ok {
				if b != cfg.Desc {
					return nil, fmt.Errorf("inconsisting sorting direction for %q binding", cfg.Binding)
				}
				dups = true
			} else {
				seen[cfg.Binding] = cfg.Desc
			}
			// Check that the binding exist.
			if _, ok := outs[cfg.Binding]; !ok {
				return nil, fmt.Errorf("order by binding %q unknown; available bindings are %v", cfg.Binding, s.OutputBindings())
			}
		}
		// If dups exist rewrite the order by SortConfig.
		if dups {
			s.orderBy = table.SortConfig{}
			for b, d := range seen {
				s.orderBy = append(s.orderBy, table.SortConfig{{Binding: b, Desc: d}}...)
			}
		}
		return f, nil
	}
	return f
}
1233476
func (q Query) OrderBy(selector func(interface{}) interface{}) OrderedQuery {
	return OrderedQuery{
		orders:   []order{{selector: selector}},
		original: q,
		Query: Query{
			Iterate: func() Iterator {
				items := q.sort([]order{{selector: selector}})
				len := len(items)
				index := 0

				return func() (item interface{}, ok bool) {
					ok = index < len
					if ok {
						item = items[index]
						index++
					}

					return
				}
			},
		},
	}
}
1034916
func (statement *Statement) SQL(query interface{}, args ...interface{}) *Statement {
	switch query.(type) {
	case (*builder.Builder):
		var err error
		statement.RawSQL, statement.RawParams, err = query.(*builder.Builder).ToSQL()
		if err != nil {
			statement.Engine.logger.Error(err)
		}
	case string:
		statement.RawSQL = query.(string)
		statement.RawParams = args
	default:
		statement.Engine.logger.Error("unsupported sql type")
	}

	return statement
}
90915
func (b *SelectBuilder) ToCql() (stmt string, names []string) {
	cql := bytes.Buffer{}

	cql.WriteString("SELECT ")
	switch {
	case len(b.distinct) > 0:
		cql.WriteString("DISTINCT ")
		b.distinct.writeCql(&cql)
	case len(b.groupBy) > 0:
		b.groupBy.writeCql(&cql)
		if len(b.columns) != 0 {
			cql.WriteByte(',')
			b.columns.writeCql(&cql)
		}
	case len(b.columns) == 0:
		cql.WriteByte('*')
	default:
		b.columns.writeCql(&cql)
	}
	cql.WriteString(" FROM ")
	cql.WriteString(b.table)
	cql.WriteByte(' ')

	names = b.where.writeCql(&cql)

	if len(b.groupBy) > 0 {
		cql.WriteString("GROUP BY ")
		b.groupBy.writeCql(&cql)
		cql.WriteByte(' ')
	}

	if len(b.orderBy) > 0 {
		cql.WriteString("ORDER BY ")
		b.orderBy.writeCql(&cql)
		cql.WriteByte(' ')
	}

	if b.limit != 0 {
		cql.WriteString("LIMIT ")
		cql.WriteString(fmt.Sprint(b.limit))
		cql.WriteByte(' ')
	}

	if b.limitPerPartition != 0 {
		cql.WriteString("PER PARTITION LIMIT ")
		cql.WriteString(fmt.Sprint(b.limitPerPartition))
		cql.WriteByte(' ')
	}

	if b.allowFiltering {
		cql.WriteString("ALLOW FILTERING ")
	}

	stmt = cql.String()
	return
}
314524
func (b *SelectBuilder) OrderBy(exprs ...interface{}) *SelectBuilder {
	b.Select.OrderBy = makeOrderBy(exprs...)
	return b
}
963201
func (q *Query) First() error {
	err := q.model.Table().checkPKs()
	if err != nil {
		return err
	}

	b := appendColumns(nil, q.model.Table().Alias, q.model.Table().PKs)
	return q.OrderExpr(internal.BytesToString(b)).Limit(1).Select()
}