-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcreate_index.go
81 lines (69 loc) · 1.78 KB
/
create_index.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
package sqlbuilder
import (
"bytes"
"strings"
)
//
// Author: 陈永佳 [email protected], [email protected]
//
type CreateIndexBuilder struct {
ctx *SQLContext
table string
name string
columns []string
unique bool
}
func newCreateIndex(ctx *SQLContext, indexName string) *CreateIndexBuilder {
return &CreateIndexBuilder{
ctx: ctx,
name: indexName,
columns: make([]string, 0),
}
}
func (slf *CreateIndexBuilder) Unique() *CreateIndexBuilder {
slf.unique = true
return slf
}
func (slf *CreateIndexBuilder) OnTable(table string) *CreateIndexBuilder {
slf.table = table
return slf
}
func (slf *CreateIndexBuilder) Column(name string, desc bool) *CreateIndexBuilder {
var column string
if desc {
column = slf.ctx.escapeName(name) + SQLSpace + "DESC"
} else {
column = slf.ctx.escapeName(column)
}
slf.columns = append(slf.columns, column)
return slf
}
func (slf *CreateIndexBuilder) Columns(columns ...string) *CreateIndexBuilder {
slf.columns = append(slf.columns, MapStr(columns, slf.ctx.escapeName)...)
return slf
}
func (slf *CreateIndexBuilder) build() *bytes.Buffer {
if "" == slf.table {
panic("table not found, you should call 'Table(table)' method to set it")
}
buf := new(bytes.Buffer)
buf.WriteString("CREATE ")
if slf.unique {
buf.WriteString("UNIQUE ")
}
buf.WriteString("INDEX ")
buf.WriteString(slf.ctx.escapeName(slf.name))
buf.WriteString(" ON ")
buf.WriteString(slf.ctx.escapeName(slf.table))
buf.WriteByte('(')
// 在输入时已经转义
buf.WriteString(strings.Join(slf.columns, SQLComma))
buf.WriteByte(')')
return buf
}
func (slf *CreateIndexBuilder) ToSQL() string {
return sqlEndpoint(slf.build())
}
func (slf *CreateIndexBuilder) Execute() *Executor {
return newExecute(slf.ToSQL(), slf.ctx.prepare)
}