-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.go
79 lines (68 loc) · 1.64 KB
/
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
package spoon
import (
"fmt"
"strings"
)
// Indexes are alias of index slices.
type Indexes []*Index
// Index holds the necessary information to construct Index.
type Index struct {
name string
tableName string
isUnique bool
nullFiltered bool
keyParts []KeyPart
}
// CreateIndexSchema return `CREATE INDEX` schema.
func (i *Index) CreateIndexSchema() string {
var keyPartsStr []string
for _, kp := range i.keyParts {
kps := Quote(kp.ColumnName)
if kp.IsOrderDesc {
kps += " DESC"
}
keyPartsStr = append(keyPartsStr, kps)
}
words := make([]string, 0, 4)
words = append(words, "CREATE")
if i.isUnique {
words = append(words, "UNIQUE")
}
if i.nullFiltered {
words = append(words, "NULL_FILTERED")
}
words = append(words, "INDEX")
schema := fmt.Sprintf(
"%s %s ON %s (%s)",
strings.Join(words, " "),
Quote(i.name),
Quote(i.tableName),
strings.Join(keyPartsStr, ", "),
)
return schema
}
// DropIndexSchema return `DROP INDEX` schema.
func (i *Index) DropIndexSchema() string {
schema := fmt.Sprintf("DROP INDEX %s", Quote(i.name))
return schema
}
// AddIndex creates Index.
func AddIndex(idxName, tableName string, nullFiltered bool, keyParts ...KeyPart) *Index {
return &Index{
name: idxName,
keyParts: keyParts,
tableName: tableName,
isUnique: false,
nullFiltered: nullFiltered,
}
}
// AddUniqueIndex creates Unique Index.
func AddUniqueIndex(idxName, tableName string, nullFiltered bool, keyParts ...KeyPart) *Index {
return &Index{
name: idxName,
keyParts: keyParts,
tableName: tableName,
isUnique: true,
nullFiltered: nullFiltered,
}
}