-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.go
More file actions
220 lines (194 loc) · 5.42 KB
/
index.go
File metadata and controls
220 lines (194 loc) · 5.42 KB
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
package genddl
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"go/ast"
"log"
"reflect"
"strconv"
"strings"
"github.com/mackee/go-genddl/index"
)
const (
indexFuncName = "_schemaIndex"
indexReturnSliceType = "Definition"
indexNameMaxLength = 32
)
type indexType int
const (
indexUnique indexType = iota + 1
indexPrimaryKey
indexComplex
indexForeign
indexSpatial
indexFulltext
)
type indexer interface {
IsOuterOfCreateTable() bool
IsPlaceOnEndOfDDLFile() bool
Index(dialect Dialect, tables map[*ast.StructType]string) string
}
type indexIdent struct {
Struct *ast.StructType
Type indexType
Column []indexColumn
References []indexColumn
ForeignKeyOptions []index.ForeignKeyOption
InnerComplexIndex bool
UniqueWithName bool
ForeignKeyWithName bool
OuterForeignKey bool
OuterUniqueKey bool
}
func (si indexIdent) IsOuterOfCreateTable() bool {
if si.Type == indexComplex && !si.InnerComplexIndex {
return true
}
if si.Type == indexForeign && si.OuterForeignKey {
return true
}
if si.Type == indexUnique && si.OuterUniqueKey {
return true
}
return false
}
func (si indexIdent) IsPlaceOnEndOfDDLFile() bool {
return si.Type == indexForeign && si.OuterForeignKey
}
func (si indexIdent) Index(dialect Dialect, tables map[*ast.StructType]string) string {
bs := &bytes.Buffer{}
switch si.Type {
case indexUnique:
if si.OuterUniqueKey {
tableName := tables[si.Struct]
fmt.Fprintf(bs, "CREATE UNIQUE INDEX %s ON %s (", tableName+"_"+joinAndStripName(si.Name()), dialect.QuoteField(tableName))
} else {
if si.UniqueWithName {
fmt.Fprintf(bs, " UNIQUE %s (", joinAndStripName(si.Name()))
} else {
bs.WriteString(" UNIQUE (")
}
}
case indexPrimaryKey:
bs.WriteString(" PRIMARY KEY (")
case indexComplex:
if si.InnerComplexIndex {
fmt.Fprintf(bs, " INDEX %s (", joinAndStripName(si.Name()))
} else {
tableName := tables[si.Struct]
fmt.Fprintf(bs, "CREATE INDEX %s ON %s (", tableName+"_"+joinAndStripName(si.Name()), dialect.QuoteField(tableName))
}
case indexForeign:
tableName := tables[si.Struct]
constraintName := joinAndStripName(strings.Join([]string{"fk", tableName, si.Name()}, "_"))
if si.OuterForeignKey {
fmt.Fprintf(
bs,
"ALTER TABLE %s ADD CONSTRAINT %s ",
dialect.QuoteField(tableName),
dialect.QuoteField(constraintName),
)
} else {
bs.WriteString(" ")
}
if si.ForeignKeyWithName {
fmt.Fprintf(bs, "FOREIGN KEY %s (", joinAndStripName(si.Name()))
} else {
bs.WriteString("FOREIGN KEY (")
}
case indexSpatial:
fmt.Fprintf(bs, " SPATIAL KEY %s (", joinAndStripName(si.Name()))
case indexFulltext:
fmt.Fprintf(bs, " FULLTEXT KEY %s (", joinAndStripName(si.Name()))
}
columns := []string{}
for _, column := range si.Column {
columnName, err := column.Column(dialect, si.Struct, tables)
if err != nil {
log.Fatalf("[ERROR] cannot resolve column error: %s", err)
}
columns = append(columns, columnName)
}
bs.WriteString(strings.Join(columns, ", "))
bs.WriteString(")")
if si.Type == indexForeign {
bs.WriteString(" REFERENCES ")
if len(si.References) == 0 {
log.Fatalf("[ERROR] specified references column is invalid")
}
references, err := si.References[0].Column(dialect, si.Struct, tables)
if err != nil {
log.Fatalf("[ERROR] cannot resolve foreign references column error: %s", err)
}
bs.WriteString(references)
bs.WriteString(" ")
var options []string
for _, option := range si.ForeignKeyOptions {
o := dialect.ForeignKey(option)
options = append(options, o)
}
s := strings.Join(options, " ")
bs.WriteString(s)
}
return bs.String()
}
func (si indexIdent) Name() string {
var columnNames []string
for _, column := range si.Column {
columnNames = append(columnNames, column.ColumnName())
}
return strings.Join(columnNames, "_")
}
func joinAndStripName(s string) string {
if len(s) <= indexNameMaxLength {
return s
}
hs := sha1.Sum([]byte(s))
he := hex.EncodeToString(hs[:])
return s[:indexNameMaxLength-8] + he[:8]
}
type rawIndex string
func (rs rawIndex) IsOuterOfCreateTable() bool {
return false
}
func (rs rawIndex) IsPlaceOnEndOfDDLFile() bool {
return false
}
func (rs rawIndex) Index(dialect Dialect, tables map[*ast.StructType]string) string {
return " " + string(rs)
}
type indexColumn interface {
Column(dialect Dialect, me *ast.StructType, tables map[*ast.StructType]string) (string, error)
ColumnName() string
}
type unresolvedIndexColumn struct {
StructName string
Struct *ast.StructType
Field *ast.Field
}
func (c unresolvedIndexColumn) ColumnName() string {
field := c.Field
tv, err := strconv.Unquote(field.Tag.Value)
if err != nil {
log.Fatalf("[ERROR] struct tag is not valid: %s", err)
}
tag := reflect.StructTag(tv)
info := strings.SplitN(tag.Get("db"), ",", 2)
columnName := info[0]
return columnName
}
func (c unresolvedIndexColumn) bareColumn(dialect Dialect) string {
return dialect.QuoteField(c.ColumnName())
}
func (c unresolvedIndexColumn) Column(dialect Dialect, me *ast.StructType, tables map[*ast.StructType]string) (string, error) {
bareColumn := c.bareColumn(dialect)
if me == c.Struct {
return bareColumn, nil
}
if tableName, ok := tables[c.Struct]; ok {
return dialect.QuoteField(tableName) + "(" + bareColumn + ")", nil
}
return "", fmt.Errorf("specified column is not define table struct: %s.%s", c.StructName, c.Field.Names[0].Name)
}