gen.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package gen
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/tal-tech/go-zero/tools/goctl/config"
  9. "github.com/tal-tech/go-zero/tools/goctl/model/sql/model"
  10. "github.com/tal-tech/go-zero/tools/goctl/model/sql/parser"
  11. "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
  12. modelutil "github.com/tal-tech/go-zero/tools/goctl/model/sql/util"
  13. "github.com/tal-tech/go-zero/tools/goctl/util"
  14. "github.com/tal-tech/go-zero/tools/goctl/util/console"
  15. "github.com/tal-tech/go-zero/tools/goctl/util/format"
  16. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  17. )
  18. const (
  19. pwd = "."
  20. createTableFlag = `(?m)^(?i)CREATE\s+TABLE` // ignore case
  21. )
  22. type (
  23. defaultGenerator struct {
  24. // source string
  25. dir string
  26. console.Console
  27. pkg string
  28. cfg *config.Config
  29. }
  30. Option func(generator *defaultGenerator)
  31. )
  32. func NewDefaultGenerator(dir string, cfg *config.Config, opt ...Option) (*defaultGenerator, error) {
  33. if dir == "" {
  34. dir = pwd
  35. }
  36. dirAbs, err := filepath.Abs(dir)
  37. if err != nil {
  38. return nil, err
  39. }
  40. dir = dirAbs
  41. pkg := filepath.Base(dirAbs)
  42. err = util.MkdirIfNotExist(dir)
  43. if err != nil {
  44. return nil, err
  45. }
  46. generator := &defaultGenerator{dir: dir, cfg: cfg, pkg: pkg}
  47. var optionList []Option
  48. optionList = append(optionList, newDefaultOption())
  49. optionList = append(optionList, opt...)
  50. for _, fn := range optionList {
  51. fn(generator)
  52. }
  53. return generator, nil
  54. }
  55. func WithConsoleOption(c console.Console) Option {
  56. return func(generator *defaultGenerator) {
  57. generator.Console = c
  58. }
  59. }
  60. func newDefaultOption() Option {
  61. return func(generator *defaultGenerator) {
  62. generator.Console = console.NewColorConsole()
  63. }
  64. }
  65. func (g *defaultGenerator) StartFromDDL(source string, withCache bool) error {
  66. modelList, err := g.genFromDDL(source, withCache)
  67. if err != nil {
  68. return err
  69. }
  70. return g.createFile(modelList)
  71. }
  72. func (g *defaultGenerator) StartFromInformationSchema(db string, columns map[string][]*model.Column, withCache bool) error {
  73. m := make(map[string]string)
  74. for tableName, column := range columns {
  75. table, err := parser.ConvertColumn(db, tableName, column)
  76. if err != nil {
  77. return err
  78. }
  79. code, err := g.genModel(*table, withCache)
  80. if err != nil {
  81. return err
  82. }
  83. m[table.Name.Source()] = code
  84. }
  85. return g.createFile(m)
  86. }
  87. func (g *defaultGenerator) createFile(modelList map[string]string) error {
  88. dirAbs, err := filepath.Abs(g.dir)
  89. if err != nil {
  90. return err
  91. }
  92. g.dir = dirAbs
  93. g.pkg = filepath.Base(dirAbs)
  94. err = util.MkdirIfNotExist(dirAbs)
  95. if err != nil {
  96. return err
  97. }
  98. for tableName, code := range modelList {
  99. tn := stringx.From(tableName)
  100. modelFilename, err := format.FileNamingFormat(g.cfg.NamingFormat, fmt.Sprintf("%s_model", tn.Source()))
  101. if err != nil {
  102. return err
  103. }
  104. name := modelFilename + ".go"
  105. filename := filepath.Join(dirAbs, name)
  106. if util.FileExists(filename) {
  107. g.Warning("%s already exists, ignored.", name)
  108. continue
  109. }
  110. err = ioutil.WriteFile(filename, []byte(code), os.ModePerm)
  111. if err != nil {
  112. return err
  113. }
  114. }
  115. // generate error file
  116. varFilename, err := format.FileNamingFormat(g.cfg.NamingFormat, "vars")
  117. if err != nil {
  118. return err
  119. }
  120. filename := filepath.Join(dirAbs, varFilename+".go")
  121. text, err := util.LoadTemplate(category, errTemplateFile, template.Error)
  122. if err != nil {
  123. return err
  124. }
  125. err = util.With("vars").Parse(text).SaveTo(map[string]interface{}{
  126. "pkg": g.pkg,
  127. }, filename, false)
  128. if err != nil {
  129. return err
  130. }
  131. g.Success("Done.")
  132. return nil
  133. }
  134. // ret1: key-table name,value-code
  135. func (g *defaultGenerator) genFromDDL(source string, withCache bool) (map[string]string, error) {
  136. ddlList := g.split(source)
  137. m := make(map[string]string)
  138. for _, ddl := range ddlList {
  139. table, err := parser.Parse(ddl)
  140. if err != nil {
  141. return nil, err
  142. }
  143. code, err := g.genModel(*table, withCache)
  144. if err != nil {
  145. return nil, err
  146. }
  147. m[table.Name.Source()] = code
  148. }
  149. return m, nil
  150. }
  151. type Table struct {
  152. parser.Table
  153. CacheKey map[string]Key
  154. ContainsUniqueKey bool
  155. }
  156. func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, error) {
  157. if len(in.PrimaryKey.Name.Source()) == 0 {
  158. return "", fmt.Errorf("table %s: missing primary key", in.Name.Source())
  159. }
  160. text, err := util.LoadTemplate(category, modelTemplateFile, template.Model)
  161. if err != nil {
  162. return "", err
  163. }
  164. t := util.With("model").
  165. Parse(text).
  166. GoFmt(true)
  167. m, err := genCacheKeys(in)
  168. if err != nil {
  169. return "", err
  170. }
  171. importsCode, err := genImports(withCache, in.ContainsTime())
  172. if err != nil {
  173. return "", err
  174. }
  175. var table Table
  176. table.Table = in
  177. table.CacheKey = m
  178. var containsUniqueCache = false
  179. for _, item := range table.Fields {
  180. if item.IsUniqueKey {
  181. containsUniqueCache = true
  182. break
  183. }
  184. }
  185. table.ContainsUniqueKey = containsUniqueCache
  186. varsCode, err := genVars(table, withCache)
  187. if err != nil {
  188. return "", err
  189. }
  190. insertCode, insertCodeMethod, err := genInsert(table, withCache)
  191. if err != nil {
  192. return "", err
  193. }
  194. var findCode = make([]string, 0)
  195. findOneCode, findOneCodeMethod, err := genFindOne(table, withCache)
  196. if err != nil {
  197. return "", err
  198. }
  199. ret, err := genFindOneByField(table, withCache)
  200. if err != nil {
  201. return "", err
  202. }
  203. findCode = append(findCode, findOneCode, ret.findOneMethod)
  204. updateCode, updateCodeMethod, err := genUpdate(table, withCache)
  205. if err != nil {
  206. return "", err
  207. }
  208. deleteCode, deleteCodeMethod, err := genDelete(table, withCache)
  209. if err != nil {
  210. return "", err
  211. }
  212. var list []string
  213. list = append(list, insertCodeMethod, findOneCodeMethod, ret.findOneInterfaceMethod, updateCodeMethod, deleteCodeMethod)
  214. typesCode, err := genTypes(table, strings.Join(modelutil.TrimStringSlice(list), util.NL), withCache)
  215. if err != nil {
  216. return "", err
  217. }
  218. newCode, err := genNew(table, withCache)
  219. if err != nil {
  220. return "", err
  221. }
  222. output, err := t.Execute(map[string]interface{}{
  223. "pkg": g.pkg,
  224. "imports": importsCode,
  225. "vars": varsCode,
  226. "types": typesCode,
  227. "new": newCode,
  228. "insert": insertCode,
  229. "find": strings.Join(findCode, "\n"),
  230. "update": updateCode,
  231. "delete": deleteCode,
  232. "extraMethod": ret.cacheExtra,
  233. })
  234. if err != nil {
  235. return "", err
  236. }
  237. return output.String(), nil
  238. }
  239. func wrapWithRawString(v string) string {
  240. if v == "`" {
  241. return v
  242. }
  243. if !strings.HasPrefix(v, "`") {
  244. v = "`" + v
  245. }
  246. if !strings.HasSuffix(v, "`") {
  247. v = v + "`"
  248. } else if len(v) == 1 {
  249. v = v + "`"
  250. }
  251. return v
  252. }