github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/sqlbase/ordering.go (about) 1 // Copyright 2016 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package sqlbase 12 13 import ( 14 "github.com/cockroachdb/cockroach/pkg/sql/sem/tree" 15 "github.com/cockroachdb/cockroach/pkg/util/encoding" 16 ) 17 18 // ColumnOrderInfo describes a column (as an index) and a desired order 19 // direction. 20 type ColumnOrderInfo struct { 21 ColIdx int 22 Direction encoding.Direction 23 } 24 25 // ColumnOrdering is used to describe a desired column ordering. For example, 26 // []ColumnOrderInfo{ {3, encoding.Descending}, {1, encoding.Ascending} } 27 // represents an ordering first by column 3 (descending), then by column 1 (ascending). 28 type ColumnOrdering []ColumnOrderInfo 29 30 // NoOrdering is used to indicate an empty ColumnOrdering. 31 var NoOrdering ColumnOrdering 32 33 // CompareDatums compares two datum rows according to a column ordering. Returns: 34 // - 0 if lhs and rhs are equal on the ordering columns; 35 // - less than 0 if lhs comes first; 36 // - greater than 0 if rhs comes first. 37 func CompareDatums(ordering ColumnOrdering, evalCtx *tree.EvalContext, lhs, rhs tree.Datums) int { 38 for _, c := range ordering { 39 // TODO(pmattis): This is assuming that the datum types are compatible. I'm 40 // not sure this always holds as `CASE` expressions can return different 41 // types for a column for different rows. Investigate how other RDBMs 42 // handle this. 43 if cmp := lhs[c.ColIdx].Compare(evalCtx, rhs[c.ColIdx]); cmp != 0 { 44 if c.Direction == encoding.Descending { 45 cmp = -cmp 46 } 47 return cmp 48 } 49 } 50 return 0 51 }