command.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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/wuntsong-org/go-zero-plus/core/collection"
  9. "github.com/wuntsong-org/go-zero-plus/core/logx"
  10. "github.com/wuntsong-org/go-zero-plus/core/stores/postgres"
  11. "github.com/wuntsong-org/go-zero-plus/core/stores/sqlx"
  12. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/config"
  13. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/model/sql/command/migrationnotes"
  14. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/model/sql/gen"
  15. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/model/sql/model"
  16. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/model/sql/util"
  17. file "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/util"
  18. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/util/console"
  19. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/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 goctlwt 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. return fromPostgreSqlDataSource(url, pattern, dir, schema, cfg, cache, idea, VarBoolStrict)
  202. }
  203. type ddlArg struct {
  204. src, dir string
  205. cfg *config.Config
  206. cache, idea bool
  207. database string
  208. strict bool
  209. ignoreColumns []string
  210. }
  211. func fromDDL(arg ddlArg) error {
  212. log := console.NewConsole(arg.idea)
  213. src := strings.TrimSpace(arg.src)
  214. if len(src) == 0 {
  215. return errors.New("expected path or path globbing patterns, but nothing found")
  216. }
  217. files, err := util.MatchFiles(src)
  218. if err != nil {
  219. return err
  220. }
  221. if len(files) == 0 {
  222. return errNotMatched
  223. }
  224. generator, err := gen.NewDefaultGenerator(arg.dir, arg.cfg,
  225. gen.WithConsoleOption(log), gen.WithIgnoreColumns(arg.ignoreColumns))
  226. if err != nil {
  227. return err
  228. }
  229. for _, file := range files {
  230. err = generator.StartFromDDL(file, arg.cache, arg.strict, arg.database)
  231. if err != nil {
  232. return err
  233. }
  234. }
  235. return nil
  236. }
  237. type dataSourceArg struct {
  238. url, dir string
  239. tablePat pattern
  240. cfg *config.Config
  241. cache, idea bool
  242. strict bool
  243. ignoreColumns []string
  244. }
  245. func fromMysqlDataSource(arg dataSourceArg) error {
  246. log := console.NewConsole(arg.idea)
  247. if len(arg.url) == 0 {
  248. log.Error("%v", "expected data source of mysql, but nothing found")
  249. return nil
  250. }
  251. if len(arg.tablePat) == 0 {
  252. log.Error("%v", "expected table or table globbing patterns, but nothing found")
  253. return nil
  254. }
  255. dsn, err := mysql.ParseDSN(arg.url)
  256. if err != nil {
  257. return err
  258. }
  259. logx.Disable()
  260. databaseSource := strings.TrimSuffix(arg.url, "/"+dsn.DBName) + "/information_schema"
  261. db := sqlx.NewMysql(databaseSource)
  262. im := model.NewInformationSchemaModel(db)
  263. tables, err := im.GetAllTables(dsn.DBName)
  264. if err != nil {
  265. return err
  266. }
  267. matchTables := make(map[string]*model.Table)
  268. for _, item := range tables {
  269. if !arg.tablePat.Match(item) {
  270. continue
  271. }
  272. columnData, err := im.FindColumns(dsn.DBName, item)
  273. if err != nil {
  274. return err
  275. }
  276. table, err := columnData.Convert()
  277. if err != nil {
  278. return err
  279. }
  280. matchTables[item] = table
  281. }
  282. if len(matchTables) == 0 {
  283. return errors.New("no tables matched")
  284. }
  285. generator, err := gen.NewDefaultGenerator(arg.dir, arg.cfg,
  286. gen.WithConsoleOption(log), gen.WithIgnoreColumns(arg.ignoreColumns))
  287. if err != nil {
  288. return err
  289. }
  290. return generator.StartFromInformationSchema(matchTables, arg.cache, arg.strict)
  291. }
  292. func fromPostgreSqlDataSource(url, pattern, dir, schema string, cfg *config.Config, cache, idea, strict bool) error {
  293. log := console.NewConsole(idea)
  294. if len(url) == 0 {
  295. log.Error("%v", "expected data source of postgresql, but nothing found")
  296. return nil
  297. }
  298. if len(pattern) == 0 {
  299. log.Error("%v", "expected table or table globbing patterns, but nothing found")
  300. return nil
  301. }
  302. db := postgres.New(url)
  303. im := model.NewPostgreSqlModel(db)
  304. tables, err := im.GetAllTables(schema)
  305. if err != nil {
  306. return err
  307. }
  308. matchTables := make(map[string]*model.Table)
  309. for _, item := range tables {
  310. match, err := filepath.Match(pattern, item)
  311. if err != nil {
  312. return err
  313. }
  314. if !match {
  315. continue
  316. }
  317. columnData, err := im.FindColumns(schema, item)
  318. if err != nil {
  319. return err
  320. }
  321. table, err := columnData.Convert()
  322. if err != nil {
  323. return err
  324. }
  325. matchTables[item] = table
  326. }
  327. if len(matchTables) == 0 {
  328. return errors.New("no tables matched")
  329. }
  330. generator, err := gen.NewDefaultGenerator(dir, cfg, gen.WithConsoleOption(log), gen.WithPostgreSql())
  331. if err != nil {
  332. return err
  333. }
  334. return generator.StartFromInformationSchema(matchTables, cache, strict)
  335. }