gen.go 9.5 KB

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