-
Notifications
You must be signed in to change notification settings - Fork 2
/
column.go
336 lines (287 loc) · 9.55 KB
/
column.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package sol
import (
"fmt"
"reflect"
"github.com/aodin/sol/dialect"
"github.com/aodin/sol/types"
)
// Columnar is the interface that all dialects of a SQL column must implement
type Columnar interface {
// Two methods for neutral SQL element interfaces:
// (1) Require the interface to return the neutral implementation
// (2) Enumerate all the methods an implmentation would require
// Columnar and Tabular both use method (1)
// Name has been left as a legacy shortcut but may be removed
Compiles
Selectable
Name() string
Column() ColumnElem
Table() *TableElem
}
// ColumnElem is a dialect neutral implementation of a SQL column
type ColumnElem struct {
operators []Operator
name string
alias string
table *TableElem
datatype types.Type
invalid bool // columns will be assumed valid until otherwise proven
}
var _ Columnar = ColumnElem{}
func (col ColumnElem) AddOperator(op Operator) ColumnElem {
col.operators = append([]Operator{op}, col.operators...) // prepend
return col
}
// Alias returns the Column's alias
func (col ColumnElem) Alias() string {
return col.alias
}
// As sets an alias and returns a copy of the ColumnElem
func (col ColumnElem) As(alias string) ColumnElem {
col.alias = alias
return col
}
// Column returns a copy of its receiver Column. This method implements
// the Columnar interface.
func (col ColumnElem) Column() ColumnElem {
return col
}
// Columns returns the ColumnElem itself in a slice of ColumnElem. This
// method implements the Selectable interface.
func (col ColumnElem) Columns() []ColumnElem {
return []ColumnElem{col}
}
// Compile produces the dialect specific SQL and adds any parameters
// in the clause to the given Parameters instance
func (col ColumnElem) Compile(d dialect.Dialect, ps *Parameters) (string, error) {
str := col.FullName()
for _, op := range col.operators {
str = op.Wrap(str)
}
return str, nil
}
// Create implements the Creatable interface that outputs a column of a
// CREATE TABLE statement.
func (col ColumnElem) Create(d dialect.Dialect) (string, error) {
compiled, err := col.datatype.Create(d)
if err != nil {
return "", err
}
return fmt.Sprintf(`%s %s`, col.Name(), compiled), nil
}
// FullName prefixes the column name with the table name
// It does not include operators (such as 'max')
func (col ColumnElem) FullName() string {
return fmt.Sprintf(`%s.%s`, col.table.Name(), col.name)
}
// IsInvalid will return true when a column that does not exist was
// created by a table function - such as .Column() or .C()
func (col ColumnElem) IsInvalid() bool {
return col.invalid
}
// IsValid returns true unless the column has been marked invalid. It
// may be a false positive.
func (col ColumnElem) IsValid() bool {
return !col.IsInvalid()
}
// Name returns the name of the column - unescaped and without an alias
func (col ColumnElem) Name() string {
return fmt.Sprintf(`%s`, col.name)
}
// Modify implements the Modifier interface, allowing the ColumnElem to
// modify the given TableElem.
func (col ColumnElem) Modify(tabular Tabular) error {
if tabular == nil || tabular.Table() == nil {
return fmt.Errorf(
"sol: column %s cannot modify a nil table",
col.name,
)
}
table := tabular.Table() // Get the dialect neutral table
if err := isValidColumnName(col.name); err != nil {
return err
}
// Add the table to the column
if col.table != nil {
return fmt.Errorf(
"sol: column %s already belongs to table %s",
col.name, col.table.Name(),
)
}
col.table = table
// Add the column to the table
var err error
if table.columns, err = table.columns.Add(col); err != nil {
return err
}
// Add the type to the table creates
table.creates = append(table.creates, col)
return nil
}
// Table returns the column's Table
func (col ColumnElem) Table() *TableElem {
return col.table
}
// Type returns the column's data type
func (col ColumnElem) Type() types.Type {
return col.datatype
}
// Conditionals
// ----
const (
Equal = "="
NotEqual = "<>"
GreaterThan = ">"
GreaterThanOrEqual = ">="
LessThan = "<"
LessThanOrEqual = "<="
)
func (col ColumnElem) operator(op string, param interface{}) BinaryClause {
clause, ok := param.(Clause)
if !ok {
// The param does not implement Clause - parameterize!
clause = &Parameter{Value: param}
}
return BinaryClause{
Pre: col,
Post: clause,
Sep: fmt.Sprintf(" %s ", op),
}
}
// Equals creates an equals clause that can be used in conditional clauses.
// table.Select().Where(table.C("id").Equals(3))
func (col ColumnElem) Equals(param interface{}) BinaryClause {
return col.operator(Equal, param)
}
// DoesNotEqual creates a does not equal clause that can be used in
// conditional clauses.
// table.Select().Where(table.C("id").DoesNotEqual(3))
func (col ColumnElem) DoesNotEqual(param interface{}) BinaryClause {
return col.operator(NotEqual, param)
}
// LessThan creates a less than clause that can be used in conditional clauses.
// table.Select().Where(table.C("id").LessThan(3))
func (col ColumnElem) LessThan(param interface{}) BinaryClause {
return col.operator(LessThan, param)
}
// GreaterThan creates a greater than clause that can be used in conditional
// clauses.
// table.Select().Where(table.C("id").GreaterThan(3))
func (col ColumnElem) GreaterThan(param interface{}) BinaryClause {
return col.operator(GreaterThan, param)
}
// LTE creates a less than or equal to clause that can be used in conditional
// clauses.
// table.Select().Where(table.C("id").LTE(3))
func (col ColumnElem) LTE(param interface{}) BinaryClause {
return col.operator(LessThanOrEqual, param)
}
// GTE creates a greater than or equal to clause that can be used in
// conditional clauses.
// table.Select().Where(table.C("id").GTE(3))
func (col ColumnElem) GTE(param interface{}) BinaryClause {
return col.operator(GreaterThanOrEqual, param)
}
// IsNull creates a comparison clause that can be used for checking existence
// of NULLs in conditional clauses.
// table.Select().Where(table.C("name").IsNull())
func (col ColumnElem) IsNull() UnaryClause {
return UnaryClause{Pre: col, Sep: " IS NULL"}
}
// IsNotNull creates a comparison clause that can be used for checking absence
// of NULLs in conditional clauses.
// table.Select().Where(table.C("name").IsNotNull())
func (col ColumnElem) IsNotNull() UnaryClause {
return UnaryClause{Pre: col, Sep: " IS NOT NULL"}
}
// Like creates a pattern matching clause that can be used in conditional
// clauses.
// table.Select().Where(table.C["name"].Like(`_b%`))
func (col ColumnElem) Like(search string) BinaryClause {
return col.operator(" LIKE ", search)
}
// NotLike creates a pattern matching clause that can be used in conditional
// clauses.
// table.Select().Where(table.C("name").NotLike(`_b%`))
func (col ColumnElem) NotLike(search string) BinaryClause {
return col.operator(" NOT LIKE ", search)
}
// ILike creates a case insensitive pattern matching clause that can be
// used in conditional clauses.
// table.Select().Where(table.C("name").ILike(`_b%`))
func (col ColumnElem) ILike(search string) BinaryClause {
return col.operator(" ILIKE ", search)
}
// NotILike creates a negated, case insensitive pattern matching clause
func (col ColumnElem) NotILike(search string) BinaryClause {
return col.operator(" NOT ILIKE ", search)
}
// In creates a comparison clause with an IN operator that can be used in
// conditional clauses. An interface is used because the args may be of any
// type: ints, strings...
// table.Select().Where(table.C("id").In([]int64{1, 2, 3}))
func (col ColumnElem) In(args interface{}) BinaryClause {
// Create the inner array clause and parameters
a := ArrayClause{clauses: make([]Clause, 0), sep: ", "}
// Use reflect to get arguments from the interface only if it is a slice
s := reflect.ValueOf(args)
switch s.Kind() {
case reflect.Slice:
for i := 0; i < s.Len(); i++ {
a.clauses = append(a.clauses, &Parameter{s.Index(i).Interface()})
}
}
// TODO What if something other than a slice is given?
// TODO This statement should be able to take clauses / subqueries
return BinaryClause{
Pre: col,
Post: FuncClause{Inner: a},
Sep: " IN ",
}
}
func (col ColumnElem) Between(a, b interface{}) Clause {
return AllOf(col.GTE(a), col.LTE(b))
}
func (col ColumnElem) NotBetween(a, b interface{}) Clause {
return AnyOf(col.LessThan(a), col.GreaterThan(b))
}
// Ordering
// ----
// Orderable implements the Orderable interface that allows the column
// to be used in an ORDER BY clause.
func (col ColumnElem) Orderable() OrderedColumn {
return OrderedColumn{inner: col}
}
// Asc returns an OrderedColumn. It is the same as passing the column itself
// to an ORDER BY clause.
func (col ColumnElem) Asc() OrderedColumn {
return OrderedColumn{inner: col}
}
// Desc returns an OrderedColumn that will sort in descending order.
func (col ColumnElem) Desc() OrderedColumn {
return OrderedColumn{inner: col, desc: true}
}
// NullsFirst returns an OrderedColumn that will sort NULLs first.
func (col ColumnElem) NullsFirst() OrderedColumn {
return OrderedColumn{inner: col, nullsFirst: true}
}
// NullsLast returns an OrderedColumn that will sort NULLs last.
func (col ColumnElem) NullsLast() OrderedColumn {
return OrderedColumn{inner: col, nullsLast: true}
}
// Column is the constructor for a ColumnElem
func Column(name string, datatype types.Type) ColumnElem {
return ColumnElem{
name: name,
datatype: datatype,
}
}
// InvalidColumn creates an invalid ColumnElem
func InvalidColumn(name string, tabular Tabular) (column ColumnElem) {
column.invalid = true
column.name = name
if tabular != nil {
column.table = tabular.Table()
}
return
}