forked from yunionio/sqlchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstraint.go
More file actions
67 lines (60 loc) · 1.81 KB
/
constraint.go
File metadata and controls
67 lines (60 loc) · 1.81 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
package sqlchemy
import (
"regexp"
"strings"
)
type STableConstraint struct {
name string
columns []string
foreignTable string
foreignKeys []string
}
const (
indexPattern = `(?P<unique>UNIQUE\s+)?KEY ` + "`" + `(?P<name>\w+)` + "`" + ` \((?P<cols>` + "`" + `\w+` + "`" + `(\(\d+\))?(,\s*` + "`" + `\w+` + "`" + `(\(\d+\))?)*)\)`
constraintPattern = `CONSTRAINT ` + "`" + `(?P<name>\w+)` + "`" + ` FOREIGN KEY \((?P<cols>` + "`" + `\w+` + "`" + `(,\s*` + "`" + `\w+` + "`" + `)*)\) REFERENCES ` + "`" + `(?P<table>\w+)` + "`" + ` \((?P<fcols>` + "`" + `\w+` + "`" + `(,\s*` + "`" + `\w+` + "`" + `)*)\)`
)
var (
indexRegexp = regexp.MustCompile(indexPattern)
constraintRegexp = regexp.MustCompile(constraintPattern)
)
func fetchColumns(match string) []string {
ret := make([]string, 0)
if len(match) > 0 {
for _, part := range strings.Split(match, ",") {
if part[len(part)-1] == ')' {
part = part[:strings.LastIndexByte(part, '(')]
}
part = strings.Trim(part, "`")
if len(part) > 0 {
ret = append(ret, part)
}
}
}
// log.Debugf("%s", ret)
return ret
}
func parseConstraints(defStr string) []STableConstraint {
matches := constraintRegexp.FindAllStringSubmatch(defStr, -1)
tcs := make([]STableConstraint, len(matches))
for i := range matches {
tcs[i] = STableConstraint{
name: matches[i][1],
foreignTable: matches[i][4],
columns: fetchColumns(matches[i][2]),
foreignKeys: fetchColumns(matches[i][5]),
}
}
return tcs
}
func parseIndexes(defStr string) []STableIndex {
matches := indexRegexp.FindAllStringSubmatch(defStr, -1)
tcs := make([]STableIndex, len(matches))
for i := range matches {
tcs[i] = STableIndex{
name: matches[i][2],
isUnique: len(matches[i][1]) > 0,
columns: fetchColumns(matches[i][3]),
}
}
return tcs
}