gen.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package gen
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "git.i2edu.net/i2/go-zero/tools/goctl/config"
  10. "git.i2edu.net/i2/go-zero/tools/goctl/model/sql/model"
  11. "git.i2edu.net/i2/go-zero/tools/goctl/model/sql/parser"
  12. "git.i2edu.net/i2/go-zero/tools/goctl/model/sql/template"
  13. modelutil "git.i2edu.net/i2/go-zero/tools/goctl/model/sql/util"
  14. "git.i2edu.net/i2/go-zero/tools/goctl/util"
  15. "git.i2edu.net/i2/go-zero/tools/goctl/util/console"
  16. "git.i2edu.net/i2/go-zero/tools/goctl/util/format"
  17. "git.i2edu.net/i2/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(tables map[string]*model.Table, withCache bool) error {
  88. m := make(map[string]string)
  89. for _, each := range tables {
  90. table, err := parser.ConvertDataType(each)
  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. PrimaryCacheKey Key
  170. UniqueCacheKey []Key
  171. ContainsUniqueCacheKey bool
  172. }
  173. func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, error) {
  174. if len(in.PrimaryKey.Name.Source()) == 0 {
  175. return "", fmt.Errorf("table %s: missing primary key", in.Name.Source())
  176. }
  177. primaryKey, uniqueKey := genCacheKeys(in)
  178. importsCode, err := genImports(withCache, in.ContainsTime())
  179. if err != nil {
  180. return "", err
  181. }
  182. var table Table
  183. table.Table = in
  184. table.PrimaryCacheKey = primaryKey
  185. table.UniqueCacheKey = uniqueKey
  186. table.ContainsUniqueCacheKey = len(uniqueKey) > 0
  187. varsCode, err := genVars(table, withCache)
  188. if err != nil {
  189. return "", err
  190. }
  191. insertCode, insertCodeMethod, err := genInsert(table, withCache)
  192. if err != nil {
  193. return "", err
  194. }
  195. findCode := make([]string, 0)
  196. findOneCode, findOneCodeMethod, err := genFindOne(table, withCache)
  197. if err != nil {
  198. return "", err
  199. }
  200. ret, err := genFindOneByField(table, withCache)
  201. if err != nil {
  202. return "", err
  203. }
  204. findCode = append(findCode, findOneCode, ret.findOneMethod)
  205. updateCode, updateCodeMethod, err := genUpdate(table, withCache)
  206. if err != nil {
  207. return "", err
  208. }
  209. deleteCode, deleteCodeMethod, err := genDelete(table, withCache)
  210. if err != nil {
  211. return "", err
  212. }
  213. var list []string
  214. list = append(list, insertCodeMethod, findOneCodeMethod, ret.findOneInterfaceMethod, updateCodeMethod, deleteCodeMethod)
  215. typesCode, err := genTypes(table, strings.Join(modelutil.TrimStringSlice(list), util.NL), withCache)
  216. if err != nil {
  217. return "", err
  218. }
  219. newCode, err := genNew(table, withCache)
  220. if err != nil {
  221. return "", err
  222. }
  223. code := &code{
  224. importsCode: importsCode,
  225. varsCode: varsCode,
  226. typesCode: typesCode,
  227. newCode: newCode,
  228. insertCode: insertCode,
  229. findCode: findCode,
  230. updateCode: updateCode,
  231. deleteCode: deleteCode,
  232. cacheExtra: ret.cacheExtra,
  233. }
  234. output, err := g.executeModel(code)
  235. if err != nil {
  236. return "", err
  237. }
  238. return output.String(), nil
  239. }
  240. func (g *defaultGenerator) executeModel(code *code) (*bytes.Buffer, error) {
  241. text, err := util.LoadTemplate(category, modelTemplateFile, template.Model)
  242. if err != nil {
  243. return nil, err
  244. }
  245. t := util.With("model").
  246. Parse(text).
  247. GoFmt(true)
  248. output, err := t.Execute(map[string]interface{}{
  249. "pkg": g.pkg,
  250. "imports": code.importsCode,
  251. "vars": code.varsCode,
  252. "types": code.typesCode,
  253. "new": code.newCode,
  254. "insert": code.insertCode,
  255. "find": strings.Join(code.findCode, "\n"),
  256. "update": code.updateCode,
  257. "delete": code.deleteCode,
  258. "extraMethod": code.cacheExtra,
  259. })
  260. if err != nil {
  261. return nil, err
  262. }
  263. return output, nil
  264. }
  265. func wrapWithRawString(v string) string {
  266. if v == "`" {
  267. return v
  268. }
  269. if !strings.HasPrefix(v, "`") {
  270. v = "`" + v
  271. }
  272. if !strings.HasSuffix(v, "`") {
  273. v = v + "`"
  274. } else if len(v) == 1 {
  275. v = v + "`"
  276. }
  277. return v
  278. }