command.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. package command
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "strings"
  6. "github.com/go-sql-driver/mysql"
  7. "github.com/spf13/cobra"
  8. "github.com/zeromicro/go-zero/core/collection"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. "github.com/zeromicro/go-zero/core/stores/postgres"
  11. "github.com/zeromicro/go-zero/core/stores/sqlx"
  12. "github.com/zeromicro/go-zero/tools/goctl/config"
  13. "github.com/zeromicro/go-zero/tools/goctl/model/sql/command/migrationnotes"
  14. "github.com/zeromicro/go-zero/tools/goctl/model/sql/gen"
  15. "github.com/zeromicro/go-zero/tools/goctl/model/sql/model"
  16. "github.com/zeromicro/go-zero/tools/goctl/model/sql/util"
  17. file "github.com/zeromicro/go-zero/tools/goctl/util"
  18. "github.com/zeromicro/go-zero/tools/goctl/util/console"
  19. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  20. )
  21. var (
  22. // VarStringSrc describes the source file of sql.
  23. VarStringSrc string
  24. // VarStringDir describes the output directory of sql.
  25. VarStringDir string
  26. // VarBoolCache describes whether the cache is enabled.
  27. VarBoolCache bool
  28. // VarBoolIdea describes whether is idea or not.
  29. VarBoolIdea bool
  30. // VarStringURL describes the dsn of the sql.
  31. VarStringURL string
  32. // VarStringSliceTable describes tables.
  33. VarStringSliceTable []string
  34. // VarStringTable describes a table of sql.
  35. VarStringTable string
  36. // VarStringStyle describes the style.
  37. VarStringStyle string
  38. // VarStringDatabase describes the database.
  39. VarStringDatabase string
  40. // VarStringSchema describes the schema of postgresql.
  41. VarStringSchema string
  42. // VarStringHome describes the goctl home.
  43. VarStringHome string
  44. // VarStringRemote describes the remote git repository.
  45. VarStringRemote string
  46. // VarStringBranch describes the git branch of the repository.
  47. VarStringBranch string
  48. // VarBoolStrict describes whether the strict mode is enabled.
  49. VarBoolStrict bool
  50. // VarStringSliceIgnoreColumns represents the columns which are ignored.
  51. VarStringSliceIgnoreColumns []string
  52. )
  53. var errNotMatched = errors.New("sql not matched")
  54. // MysqlDDL generates model code from ddl
  55. func MysqlDDL(_ *cobra.Command, _ []string) error {
  56. migrationnotes.BeforeCommands(VarStringDir, VarStringStyle)
  57. src := VarStringSrc
  58. dir := VarStringDir
  59. cache := VarBoolCache
  60. idea := VarBoolIdea
  61. style := VarStringStyle
  62. database := VarStringDatabase
  63. home := VarStringHome
  64. remote := VarStringRemote
  65. branch := VarStringBranch
  66. if len(remote) > 0 {
  67. repo, _ := file.CloneIntoGitHome(remote, branch)
  68. if len(repo) > 0 {
  69. home = repo
  70. }
  71. }
  72. if len(home) > 0 {
  73. pathx.RegisterGoctlHome(home)
  74. }
  75. cfg, err := config.NewConfig(style)
  76. if err != nil {
  77. return err
  78. }
  79. arg := ddlArg{
  80. src: src,
  81. dir: dir,
  82. cfg: cfg,
  83. cache: cache,
  84. idea: idea,
  85. database: database,
  86. strict: VarBoolStrict,
  87. ignoreColumns: mergeColumns(VarStringSliceIgnoreColumns),
  88. }
  89. return fromDDL(arg)
  90. }
  91. // MySqlDataSource generates model code from datasource
  92. func MySqlDataSource(_ *cobra.Command, _ []string) error {
  93. migrationnotes.BeforeCommands(VarStringDir, VarStringStyle)
  94. url := strings.TrimSpace(VarStringURL)
  95. dir := strings.TrimSpace(VarStringDir)
  96. cache := VarBoolCache
  97. idea := VarBoolIdea
  98. style := VarStringStyle
  99. home := VarStringHome
  100. remote := VarStringRemote
  101. branch := VarStringBranch
  102. if len(remote) > 0 {
  103. repo, _ := file.CloneIntoGitHome(remote, branch)
  104. if len(repo) > 0 {
  105. home = repo
  106. }
  107. }
  108. if len(home) > 0 {
  109. pathx.RegisterGoctlHome(home)
  110. }
  111. tableValue := VarStringSliceTable
  112. patterns := parseTableList(tableValue)
  113. cfg, err := config.NewConfig(style)
  114. if err != nil {
  115. return err
  116. }
  117. arg := dataSourceArg{
  118. url: url,
  119. dir: dir,
  120. tablePat: patterns,
  121. cfg: cfg,
  122. cache: cache,
  123. idea: idea,
  124. strict: VarBoolStrict,
  125. ignoreColumns: mergeColumns(VarStringSliceIgnoreColumns),
  126. }
  127. return fromMysqlDataSource(arg)
  128. }
  129. func mergeColumns(columns []string) []string {
  130. set := collection.NewSet()
  131. for _, v := range columns {
  132. fields := strings.FieldsFunc(v, func(r rune) bool {
  133. return r == ','
  134. })
  135. set.AddStr(fields...)
  136. }
  137. return set.KeysStr()
  138. }
  139. type pattern map[string]struct{}
  140. func (p pattern) Match(s string) bool {
  141. for v := range p {
  142. match, err := filepath.Match(v, s)
  143. if err != nil {
  144. console.Error("%+v", err)
  145. continue
  146. }
  147. if match {
  148. return true
  149. }
  150. }
  151. return false
  152. }
  153. func (p pattern) list() []string {
  154. var ret []string
  155. for v := range p {
  156. ret = append(ret, v)
  157. }
  158. return ret
  159. }
  160. func parseTableList(tableValue []string) pattern {
  161. tablePattern := make(pattern)
  162. for _, v := range tableValue {
  163. fields := strings.FieldsFunc(v, func(r rune) bool {
  164. return r == ','
  165. })
  166. for _, f := range fields {
  167. tablePattern[f] = struct{}{}
  168. }
  169. }
  170. return tablePattern
  171. }
  172. // PostgreSqlDataSource generates model code from datasource
  173. func PostgreSqlDataSource(_ *cobra.Command, _ []string) error {
  174. migrationnotes.BeforeCommands(VarStringDir, VarStringStyle)
  175. url := strings.TrimSpace(VarStringURL)
  176. dir := strings.TrimSpace(VarStringDir)
  177. cache := VarBoolCache
  178. idea := VarBoolIdea
  179. style := VarStringStyle
  180. schema := VarStringSchema
  181. home := VarStringHome
  182. remote := VarStringRemote
  183. branch := VarStringBranch
  184. if len(remote) > 0 {
  185. repo, _ := file.CloneIntoGitHome(remote, branch)
  186. if len(repo) > 0 {
  187. home = repo
  188. }
  189. }
  190. if len(home) > 0 {
  191. pathx.RegisterGoctlHome(home)
  192. }
  193. if len(schema) == 0 {
  194. schema = "public"
  195. }
  196. pattern := strings.TrimSpace(VarStringTable)
  197. cfg, err := config.NewConfig(style)
  198. if err != nil {
  199. return err
  200. }
  201. ignoreColumns := mergeColumns(VarStringSliceIgnoreColumns)
  202. return fromPostgreSqlDataSource(url, pattern, dir, schema, cfg, cache, idea, VarBoolStrict, ignoreColumns)
  203. }
  204. type ddlArg struct {
  205. src, dir string
  206. cfg *config.Config
  207. cache, idea bool
  208. database string
  209. strict bool
  210. ignoreColumns []string
  211. }
  212. func fromDDL(arg ddlArg) error {
  213. log := console.NewConsole(arg.idea)
  214. src := strings.TrimSpace(arg.src)
  215. if len(src) == 0 {
  216. return errors.New("expected path or path globbing patterns, but nothing found")
  217. }
  218. files, err := util.MatchFiles(src)
  219. if err != nil {
  220. return err
  221. }
  222. if len(files) == 0 {
  223. return errNotMatched
  224. }
  225. generator, err := gen.NewDefaultGenerator(arg.dir, arg.cfg,
  226. gen.WithConsoleOption(log), gen.WithIgnoreColumns(arg.ignoreColumns))
  227. if err != nil {
  228. return err
  229. }
  230. for _, file := range files {
  231. err = generator.StartFromDDL(file, arg.cache, arg.strict, arg.database)
  232. if err != nil {
  233. return err
  234. }
  235. }
  236. return nil
  237. }
  238. type dataSourceArg struct {
  239. url, dir string
  240. tablePat pattern
  241. cfg *config.Config
  242. cache, idea bool
  243. strict bool
  244. ignoreColumns []string
  245. }
  246. func fromMysqlDataSource(arg dataSourceArg) error {
  247. log := console.NewConsole(arg.idea)
  248. if len(arg.url) == 0 {
  249. log.Error("%v", "expected data source of mysql, but nothing found")
  250. return nil
  251. }
  252. if len(arg.tablePat) == 0 {
  253. log.Error("%v", "expected table or table globbing patterns, but nothing found")
  254. return nil
  255. }
  256. dsn, err := mysql.ParseDSN(arg.url)
  257. if err != nil {
  258. return err
  259. }
  260. logx.Disable()
  261. databaseSource := strings.TrimSuffix(arg.url, "/"+dsn.DBName) + "/information_schema"
  262. db := sqlx.NewMysql(databaseSource)
  263. im := model.NewInformationSchemaModel(db)
  264. tables, err := im.GetAllTables(dsn.DBName)
  265. if err != nil {
  266. return err
  267. }
  268. matchTables := make(map[string]*model.Table)
  269. for _, item := range tables {
  270. if !arg.tablePat.Match(item) {
  271. continue
  272. }
  273. columnData, err := im.FindColumns(dsn.DBName, item)
  274. if err != nil {
  275. return err
  276. }
  277. table, err := columnData.Convert()
  278. if err != nil {
  279. return err
  280. }
  281. matchTables[item] = table
  282. }
  283. if len(matchTables) == 0 {
  284. return errors.New("no tables matched")
  285. }
  286. generator, err := gen.NewDefaultGenerator(arg.dir, arg.cfg,
  287. gen.WithConsoleOption(log), gen.WithIgnoreColumns(arg.ignoreColumns))
  288. if err != nil {
  289. return err
  290. }
  291. return generator.StartFromInformationSchema(matchTables, arg.cache, arg.strict)
  292. }
  293. func fromPostgreSqlDataSource(url, pattern, dir, schema string, cfg *config.Config, cache, idea, strict bool, ignoreColumns []string) error {
  294. log := console.NewConsole(idea)
  295. if len(url) == 0 {
  296. log.Error("%v", "expected data source of postgresql, but nothing found")
  297. return nil
  298. }
  299. if len(pattern) == 0 {
  300. log.Error("%v", "expected table or table globbing patterns, but nothing found")
  301. return nil
  302. }
  303. db := postgres.New(url)
  304. im := model.NewPostgreSqlModel(db)
  305. tables, err := im.GetAllTables(schema)
  306. if err != nil {
  307. return err
  308. }
  309. matchTables := make(map[string]*model.Table)
  310. for _, item := range tables {
  311. match, err := filepath.Match(pattern, item)
  312. if err != nil {
  313. return err
  314. }
  315. if !match {
  316. continue
  317. }
  318. columnData, err := im.FindColumns(schema, item)
  319. if err != nil {
  320. return err
  321. }
  322. table, err := columnData.Convert()
  323. if err != nil {
  324. return err
  325. }
  326. matchTables[item] = table
  327. }
  328. if len(matchTables) == 0 {
  329. return errors.New("no tables matched")
  330. }
  331. generator, err := gen.NewDefaultGenerator(dir, cfg, gen.WithConsoleOption(log), gen.WithPostgreSql(), gen.WithIgnoreColumns(ignoreColumns))
  332. if err != nil {
  333. return err
  334. }
  335. return generator.StartFromInformationSchema(matchTables, cache, strict)
  336. }