This repository has been archived by the owner on Nov 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
generator.go
73 lines (63 loc) · 1.59 KB
/
generator.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
package main
import (
"bytes"
"log"
"regexp"
"strings"
"github.com/alecthomas/template"
"github.com/iancoleman/strcase"
)
func goName(s string) string {
s = strings.Replace(s, "[", "", -1)
s = strings.Replace(s, "]", "", -1)
s = strings.TrimPrefix(s, "@")
s = strcase.ToSnake(s)
return uppercaseIds(strcase.ToCamel(s))
}
var funcMap = template.FuncMap{
"GoNameLower": func(s string) string {
s = strings.Replace(s, "[", "", -1)
s = strings.Replace(s, "]", "", -1)
s = strings.TrimPrefix(s, "@")
s = strcase.ToSnake(s)
return uppercaseIds(strcase.ToLowerCamel(s))
},
"GoName": goName,
"GoDataType": func(s string) string {
if strings.Contains(s, "(") {
s = s[0:strings.Index(s, "(")]
}
return SQLTypeToGoType(s)
},
"Clean": func(s string) string {
s = strings.TrimPrefix(s, "@")
return stripQuotes(s)
},
}
func Generate(packageName string, result *ParseResult) (string, error) {
tmpl, err := template.New(".").Funcs(funcMap).Parse(tFile)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, map[string]interface{}{
"packageName": packageName,
"tables": result.Tables,
"normalTables": result.NormalTables,
"procedures": result.Procedures,
}); err != nil {
log.Fatal(err)
}
return string(buf.Bytes()), nil
}
func stripQuotes(s string) string {
s = strings.Replace(s, `"`, "", -1)
return strings.Replace(s, `'`, "", -1)
}
func uppercaseIds(s string) string {
var re = regexp.MustCompile(`(?m)(Id)(?:[A-Z]|$)`)
for _, match := range re.FindAllStringIndex(s, -1) {
s = s[0:match[0]] + "ID" + s[match[1]:]
}
return s
}