fieldmodel.go 1.3 KB

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