gen.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. package gen
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/zeromicro/go-zero/tools/goctl/config"
  10. "github.com/zeromicro/go-zero/tools/goctl/model/sql/model"
  11. "github.com/zeromicro/go-zero/tools/goctl/model/sql/parser"
  12. "github.com/zeromicro/go-zero/tools/goctl/model/sql/template"
  13. modelutil "github.com/zeromicro/go-zero/tools/goctl/model/sql/util"
  14. "github.com/zeromicro/go-zero/tools/goctl/util"
  15. "github.com/zeromicro/go-zero/tools/goctl/util/console"
  16. "github.com/zeromicro/go-zero/tools/goctl/util/format"
  17. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  18. "github.com/zeromicro/go-zero/tools/goctl/util/stringx"
  19. )
  20. const pwd = "."
  21. type (
  22. defaultGenerator struct {
  23. console.Console
  24. // source string
  25. dir string
  26. pkg string
  27. cfg *config.Config
  28. isPostgreSql bool
  29. ignoreColumns []string
  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. tableName string
  44. }
  45. codeTuple struct {
  46. modelCode string
  47. modelCustomCode string
  48. }
  49. )
  50. // NewDefaultGenerator creates an instance for defaultGenerator
  51. func NewDefaultGenerator(dir string, cfg *config.Config, opt ...Option) (*defaultGenerator, error) {
  52. if dir == "" {
  53. dir = pwd
  54. }
  55. dirAbs, err := filepath.Abs(dir)
  56. if err != nil {
  57. return nil, err
  58. }
  59. dir = dirAbs
  60. pkg := util.SafeString(filepath.Base(dirAbs))
  61. err = pathx.MkdirIfNotExist(dir)
  62. if err != nil {
  63. return nil, err
  64. }
  65. generator := &defaultGenerator{dir: dir, cfg: cfg, pkg: pkg}
  66. var optionList []Option
  67. optionList = append(optionList, newDefaultOption())
  68. optionList = append(optionList, opt...)
  69. for _, fn := range optionList {
  70. fn(generator)
  71. }
  72. return generator, nil
  73. }
  74. // WithConsoleOption creates a console option.
  75. func WithConsoleOption(c console.Console) Option {
  76. return func(generator *defaultGenerator) {
  77. generator.Console = c
  78. }
  79. }
  80. // WithIgnoreColumns ignores the columns while insert or update rows.
  81. func WithIgnoreColumns(ignoreColumns []string) Option {
  82. return func(generator *defaultGenerator) {
  83. generator.ignoreColumns = ignoreColumns
  84. }
  85. }
  86. // WithPostgreSql marks defaultGenerator.isPostgreSql true.
  87. func WithPostgreSql() Option {
  88. return func(generator *defaultGenerator) {
  89. generator.isPostgreSql = true
  90. }
  91. }
  92. func newDefaultOption() Option {
  93. return func(generator *defaultGenerator) {
  94. generator.Console = console.NewColorConsole()
  95. }
  96. }
  97. func (g *defaultGenerator) StartFromDDL(filename string, withCache, strict bool, database string) error {
  98. modelList, err := g.genFromDDL(filename, withCache, strict, database)
  99. if err != nil {
  100. return err
  101. }
  102. return g.createFile(modelList)
  103. }
  104. func (g *defaultGenerator) StartFromInformationSchema(tables map[string]*model.Table, withCache, strict bool) error {
  105. m := make(map[string]*codeTuple)
  106. for _, each := range tables {
  107. table, err := parser.ConvertDataType(each, strict)
  108. if err != nil {
  109. return err
  110. }
  111. code, err := g.genModel(*table, withCache)
  112. if err != nil {
  113. return err
  114. }
  115. customCode, err := g.genModelCustom(*table, withCache)
  116. if err != nil {
  117. return err
  118. }
  119. m[table.Name.Source()] = &codeTuple{
  120. modelCode: code,
  121. modelCustomCode: customCode,
  122. }
  123. }
  124. return g.createFile(m)
  125. }
  126. func (g *defaultGenerator) createFile(modelList map[string]*codeTuple) error {
  127. dirAbs, err := filepath.Abs(g.dir)
  128. if err != nil {
  129. return err
  130. }
  131. g.dir = dirAbs
  132. g.pkg = util.SafeString(filepath.Base(dirAbs))
  133. err = pathx.MkdirIfNotExist(dirAbs)
  134. if err != nil {
  135. return err
  136. }
  137. for tableName, codes := range modelList {
  138. tn := stringx.From(tableName)
  139. modelFilename, err := format.FileNamingFormat(g.cfg.NamingFormat,
  140. fmt.Sprintf("%s_model", tn.Source()))
  141. if err != nil {
  142. return err
  143. }
  144. name := util.SafeString(modelFilename) + "_gen.go"
  145. filename := filepath.Join(dirAbs, name)
  146. err = ioutil.WriteFile(filename, []byte(codes.modelCode), os.ModePerm)
  147. if err != nil {
  148. return err
  149. }
  150. name = util.SafeString(modelFilename) + ".go"
  151. filename = filepath.Join(dirAbs, name)
  152. if pathx.FileExists(filename) {
  153. g.Warning("%s already exists, ignored.", name)
  154. continue
  155. }
  156. err = ioutil.WriteFile(filename, []byte(codes.modelCustomCode), os.ModePerm)
  157. if err != nil {
  158. return err
  159. }
  160. }
  161. // generate error file
  162. varFilename, err := format.FileNamingFormat(g.cfg.NamingFormat, "vars")
  163. if err != nil {
  164. return err
  165. }
  166. filename := filepath.Join(dirAbs, varFilename+".go")
  167. text, err := pathx.LoadTemplate(category, errTemplateFile, template.Error)
  168. if err != nil {
  169. return err
  170. }
  171. err = util.With("vars").Parse(text).SaveTo(map[string]interface{}{
  172. "pkg": g.pkg,
  173. }, filename, false)
  174. if err != nil {
  175. return err
  176. }
  177. g.Success("Done.")
  178. return nil
  179. }
  180. // ret1: key-table name,value-code
  181. func (g *defaultGenerator) genFromDDL(filename string, withCache, strict bool, database string) (
  182. map[string]*codeTuple, error,
  183. ) {
  184. m := make(map[string]*codeTuple)
  185. tables, err := parser.Parse(filename, database, strict)
  186. if err != nil {
  187. return nil, err
  188. }
  189. for _, e := range tables {
  190. code, err := g.genModel(*e, withCache)
  191. if err != nil {
  192. return nil, err
  193. }
  194. customCode, err := g.genModelCustom(*e, withCache)
  195. if err != nil {
  196. return nil, err
  197. }
  198. m[e.Name.Source()] = &codeTuple{
  199. modelCode: code,
  200. modelCustomCode: customCode,
  201. }
  202. }
  203. return m, nil
  204. }
  205. // Table defines mysql table
  206. type Table struct {
  207. parser.Table
  208. PrimaryCacheKey Key
  209. UniqueCacheKey []Key
  210. ContainsUniqueCacheKey bool
  211. ignoreColumns []string
  212. }
  213. func (t Table) isIgnoreColumns(columnName string) bool {
  214. for _, v := range t.ignoreColumns {
  215. if v == columnName {
  216. return true
  217. }
  218. }
  219. return false
  220. }
  221. func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, error) {
  222. if len(in.PrimaryKey.Name.Source()) == 0 {
  223. return "", fmt.Errorf("table %s: missing primary key", in.Name.Source())
  224. }
  225. primaryKey, uniqueKey := genCacheKeys(in)
  226. var table Table
  227. table.Table = in
  228. table.PrimaryCacheKey = primaryKey
  229. table.UniqueCacheKey = uniqueKey
  230. table.ContainsUniqueCacheKey = len(uniqueKey) > 0
  231. table.ignoreColumns = g.ignoreColumns
  232. importsCode, err := genImports(table, withCache, in.ContainsTime())
  233. if err != nil {
  234. return "", err
  235. }
  236. varsCode, err := genVars(table, withCache, g.isPostgreSql)
  237. if err != nil {
  238. return "", err
  239. }
  240. insertCode, insertCodeMethod, err := genInsert(table, withCache, g.isPostgreSql)
  241. if err != nil {
  242. return "", err
  243. }
  244. findCode := make([]string, 0)
  245. findOneCode, findOneCodeMethod, err := genFindOne(table, withCache, g.isPostgreSql)
  246. if err != nil {
  247. return "", err
  248. }
  249. ret, err := genFindOneByField(table, withCache, g.isPostgreSql)
  250. if err != nil {
  251. return "", err
  252. }
  253. findCode = append(findCode, findOneCode, ret.findOneMethod)
  254. updateCode, updateCodeMethod, err := genUpdate(table, withCache, g.isPostgreSql)
  255. if err != nil {
  256. return "", err
  257. }
  258. deleteCode, deleteCodeMethod, err := genDelete(table, withCache, g.isPostgreSql)
  259. if err != nil {
  260. return "", err
  261. }
  262. var list []string
  263. list = append(list, insertCodeMethod, findOneCodeMethod, ret.findOneInterfaceMethod,
  264. updateCodeMethod, deleteCodeMethod)
  265. typesCode, err := genTypes(table, strings.Join(modelutil.TrimStringSlice(list), pathx.NL), withCache)
  266. if err != nil {
  267. return "", err
  268. }
  269. newCode, err := genNew(table, withCache, g.isPostgreSql)
  270. if err != nil {
  271. return "", err
  272. }
  273. tableName, err := genTableName(table)
  274. if err != nil {
  275. return "", err
  276. }
  277. code := &code{
  278. importsCode: importsCode,
  279. varsCode: varsCode,
  280. typesCode: typesCode,
  281. newCode: newCode,
  282. insertCode: insertCode,
  283. findCode: findCode,
  284. updateCode: updateCode,
  285. deleteCode: deleteCode,
  286. cacheExtra: ret.cacheExtra,
  287. tableName: tableName,
  288. }
  289. output, err := g.executeModel(table, code)
  290. if err != nil {
  291. return "", err
  292. }
  293. return output.String(), nil
  294. }
  295. func (g *defaultGenerator) genModelCustom(in parser.Table, withCache bool) (string, error) {
  296. text, err := pathx.LoadTemplate(category, modelCustomTemplateFile, template.ModelCustom)
  297. if err != nil {
  298. return "", err
  299. }
  300. t := util.With("model-custom").
  301. Parse(text).
  302. GoFmt(true)
  303. output, err := t.Execute(map[string]interface{}{
  304. "pkg": g.pkg,
  305. "withCache": withCache,
  306. "upperStartCamelObject": in.Name.ToCamel(),
  307. "lowerStartCamelObject": stringx.From(in.Name.ToCamel()).Untitle(),
  308. })
  309. if err != nil {
  310. return "", err
  311. }
  312. return output.String(), nil
  313. }
  314. func (g *defaultGenerator) executeModel(table Table, code *code) (*bytes.Buffer, error) {
  315. text, err := pathx.LoadTemplate(category, modelGenTemplateFile, template.ModelGen)
  316. if err != nil {
  317. return nil, err
  318. }
  319. t := util.With("model").
  320. Parse(text).
  321. GoFmt(true)
  322. output, err := t.Execute(map[string]interface{}{
  323. "pkg": g.pkg,
  324. "imports": code.importsCode,
  325. "vars": code.varsCode,
  326. "types": code.typesCode,
  327. "new": code.newCode,
  328. "insert": code.insertCode,
  329. "find": strings.Join(code.findCode, "\n"),
  330. "update": code.updateCode,
  331. "delete": code.deleteCode,
  332. "extraMethod": code.cacheExtra,
  333. "tableName": code.tableName,
  334. "data": table,
  335. })
  336. if err != nil {
  337. return nil, err
  338. }
  339. return output, nil
  340. }
  341. func wrapWithRawString(v string, postgreSql bool) string {
  342. if postgreSql {
  343. return v
  344. }
  345. if v == "`" {
  346. return v
  347. }
  348. if !strings.HasPrefix(v, "`") {
  349. v = "`" + v
  350. }
  351. if !strings.HasSuffix(v, "`") {
  352. v = v + "`"
  353. } else if len(v) == 1 {
  354. v = v + "`"
  355. }
  356. return v
  357. }