forked from slicebit/qb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtag.go
69 lines (53 loc) · 1.4 KB
/
tag.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
package qb
import (
"fmt"
"strings"
)
// Tag is the base abstraction of qb tag
type Tag struct {
// contains default, null, notnull, unique, primary_key, foreign_key(table.column), check(condition > 0)
Constraints []string
// contains type(size) or type parameters
Type string
// true if it is ignored
Ignore bool
}
// ParseTag parses raw qb tag and builds a Tag object
func ParseTag(rawTag string) (Tag, error) {
rawTag = strings.Replace(rawTag, " ", "", -1)
tag := Tag{
Constraints: []string{},
}
if rawTag == "" {
return Tag{}, nil
}
tags := strings.Split(rawTag, ";")
for _, t := range tags {
tagKeyVal := strings.Split(t, ":")
if tagKeyVal[0] == "index" {
tag.Constraints = append(tag.Constraints, t)
continue
} else if tagKeyVal[0] == "-" {
tag.Ignore = true
return Tag{Ignore: true}, nil
}
if len(tagKeyVal) != 2 {
return Tag{}, fmt.Errorf("Invalid tag key length, tag: %v", tag)
}
if tagKeyVal[0] == "type" {
tag.Type = tagKeyVal[1]
} else if tagKeyVal[0] == "constraints" || tagKeyVal[0] == "constraint" {
for _, c := range strings.Split(tagKeyVal[1], ",") {
if c != "" {
tag.Constraints = append(tag.Constraints, c)
}
}
}
}
return tag, nil
}
// ParseDBTag parses the "db" tag that can be used in custom column name mapping
func ParseDBTag(rawTag string) string {
rawTag = strings.Replace(rawTag, " ", "", -1)
return rawTag
}