/
column.go
93 lines (80 loc) · 2.07 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
package goq
// ColumnMaker is a utility to make several columns of the same table easily.
type ColumnMaker struct {
structName string
tableName string
tableAlias string
}
func NewColumnMaker(structName, tableName string) *ColumnMaker {
return &ColumnMaker{structName: structName, tableName: tableName}
}
func (m *ColumnMaker) As(alias string) *ColumnMaker {
m.tableAlias = alias
return m
}
func (m *ColumnMaker) Col(fieldName, name string) *ColumnBuilder {
col := (&Column{
tableName: m.tableName,
tableAlias: m.tableAlias,
structName: m.structName,
name: name,
fieldName: fieldName,
meta: ColumnMeta{},
}).init()
return &ColumnBuilder{col}
}
type ColumnBuilder struct {
col *Column
}
// PK specifies the column is a primary key.
func (cb *ColumnBuilder) PK() *ColumnBuilder {
cb.col.meta.PK = true
return cb
}
func (cb *ColumnBuilder) Bld() *Column {
return cb.col
}
// ColumnMeta is a meta information about a column.
type ColumnMeta struct {
// PK indicates this column is a primary key or not.
PK bool
}
// Column has data about the column and its table.
type Column struct {
tableName string
tableAlias string
structName string
name string
fieldName string
meta ColumnMeta
ops
}
func (c *Column) init() *Column {
c.ops = ops{c}
return c
}
func (c *Column) TableName() string { return c.tableName }
func (c *Column) TableAlias() string { return c.tableAlias }
func (c *Column) StructName() string { return c.structName }
func (c *Column) ColumnName() string { return c.name }
func (c *Column) FieldName() string { return c.fieldName }
func (c *Column) Meta() *ColumnMeta { return &c.meta }
func (c *Column) Apply(q *Query, ctx DBContext) {
table := c.tableAlias
if table == "" {
table = c.tableName
}
if table != "" {
q.query = append(q.query, ctx.QuoteIdent(table), ".")
}
q.query = append(q.query, ctx.QuoteIdent(c.name))
}
func (c *Column) Selection() Selection {
return Selection{
ColumnName: c.name,
TableName: c.tableName,
TableAlias: c.tableAlias,
StructName: c.structName,
FieldName: c.fieldName,
}
}