gen.go 7.3 KB

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