fieldmodel.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package modelgen
  2. import "github.com/tal-tech/go-zero/core/stores/sqlx"
  3. type (
  4. FieldModel struct {
  5. dataSource string
  6. conn sqlx.SqlConn
  7. table string
  8. }
  9. Field struct {
  10. // 字段名称,下划线
  11. Name string `db:"name"`
  12. // 字段数据类型
  13. Type string `db:"type"`
  14. // 字段顺序
  15. Position int `db:"position"`
  16. // 字段注释
  17. Comment string `db:"comment"`
  18. // key
  19. Primary string `db:"k"`
  20. }
  21. Table struct {
  22. Name string `db:"name"`
  23. }
  24. )
  25. func NewFieldModel(dataSource, table string) *FieldModel {
  26. return &FieldModel{conn: sqlx.NewMysql(dataSource), table: table}
  27. }
  28. func (fm *FieldModel) findTables() ([]string, error) {
  29. querySql := `select TABLE_NAME AS name from COLUMNS where TABLE_SCHEMA = ? GROUP BY TABLE_NAME`
  30. var tables []*Table
  31. err := fm.conn.QueryRows(&tables, querySql, fm.table)
  32. if err != nil {
  33. return nil, err
  34. }
  35. tableList := make([]string, 0)
  36. for _, item := range tables {
  37. tableList = append(tableList, item.Name)
  38. }
  39. return tableList, nil
  40. }
  41. func (fm *FieldModel) findColumns(tableName string) ([]*Field, error) {
  42. querySql := `select ` + queryRows + ` from COLUMNS where TABLE_SCHEMA = ? and TABLE_NAME = ?`
  43. var resp []*Field
  44. err := fm.conn.QueryRows(&resp, querySql, fm.table, tableName)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return resp, nil
  49. }