-
Notifications
You must be signed in to change notification settings - Fork 2
/
order.go
79 lines (68 loc) · 2.11 KB
/
order.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package sol
import (
"github.com/aodin/sol/dialect"
)
// Orderable is implemented by both ColumnElem and OrderedColumn types. It
// allows those types to be used in ORDER BY clauses.
type Orderable interface {
Orderable() OrderedColumn
}
// OrderedColumn represents a ColumnElem that will be used in an ORDER BY
// clause within SELECT statements. It provides additional sorting
// features, such as ASC, DESC, NULLS FIRST, and NULLS LAST.
// If not specified, ASC is assumed by default.
// In Postgres: the default behavior is NULLS LAST when ASC is specified or
// implied, and NULLS FIRST when DESC is specified
// http://www.postgresql.org/docs/9.2/static/sql-select.html#SQL-ORDERBY
type OrderedColumn struct {
inner Columnar
desc, nullsFirst, nullsLast bool
}
// OrderedColumn should implement the Orderable interface
var _ Orderable = OrderedColumn{}
// String outputs the OrderedColumn in a neutral dialect.
func (ord OrderedColumn) String() string {
compiled, _ := ord.Compile(&defaultDialect{}, Params())
return compiled
}
func (ord OrderedColumn) Compile(d dialect.Dialect, ps *Parameters) (string, error) {
// TODO error ignored
compiled, _ := ord.inner.Compile(d, ps)
if ord.desc {
compiled += " DESC"
}
if ord.nullsFirst || ord.nullsLast {
if ord.nullsFirst {
compiled += " NULLS FIRST"
} else {
compiled += " NULLS LAST"
}
}
return compiled, nil
}
// Orderable returns the OrderedColumn itself
func (ord OrderedColumn) Orderable() OrderedColumn {
return ord
}
// Asc sets the column ordering to ascending - the default
func (ord OrderedColumn) Asc() OrderedColumn {
ord.desc = false
return ord
}
// Desc sets the column ordering to descending
func (ord OrderedColumn) Desc() OrderedColumn {
ord.desc = true
return ord
}
// NullsFirst sets the column ordering to return NULL results first
func (ord OrderedColumn) NullsFirst() OrderedColumn {
ord.nullsFirst = true
ord.nullsLast = false
return ord
}
// NullsLast sets the column ordering to return NULL results last
func (ord OrderedColumn) NullsLast() OrderedColumn {
ord.nullsFirst = false
ord.nullsLast = true
return ord
}