db_columns.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package tools
  2. import (
  3. "errors"
  4. "github.com/go-admin-team/go-admin-core/sdk/config"
  5. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  6. "gorm.io/gorm"
  7. )
  8. type DBColumns struct {
  9. TableSchema string `gorm:"column:TABLE_SCHEMA" json:"tableSchema"`
  10. TableName string `gorm:"column:TABLE_NAME" json:"tableName"`
  11. ColumnName string `gorm:"column:COLUMN_NAME" json:"columnName"`
  12. ColumnDefault string `gorm:"column:COLUMN_DEFAULT" json:"columnDefault"`
  13. IsNullable string `gorm:"column:IS_NULLABLE" json:"isNullable"`
  14. DataType string `gorm:"column:DATA_TYPE" json:"dataType"`
  15. CharacterMaximumLength string `gorm:"column:CHARACTER_MAXIMUM_LENGTH" json:"characterMaximumLength"`
  16. CharacterSetName string `gorm:"column:CHARACTER_SET_NAME" json:"characterSetName"`
  17. ColumnType string `gorm:"column:COLUMN_TYPE" json:"columnType"`
  18. ColumnKey string `gorm:"column:COLUMN_KEY" json:"columnKey"`
  19. Extra string `gorm:"column:EXTRA" json:"extra"`
  20. ColumnComment string `gorm:"column:COLUMN_COMMENT" json:"columnComment"`
  21. }
  22. func (e *DBColumns) GetPage(tx *gorm.DB, pageSize int, pageIndex int) ([]DBColumns, int, error) {
  23. var doc []DBColumns
  24. var count int64
  25. table := new(gorm.DB)
  26. if config.DatabaseConfig.Driver == "mysql" {
  27. table = tx.Table("information_schema.`COLUMNS`")
  28. table = table.Where("table_schema= ? ", config.GenConfig.DBName)
  29. if e.TableName != "" {
  30. return nil, 0, errors.New("table name cannot be empty!")
  31. }
  32. table = table.Where("TABLE_NAME = ?", e.TableName)
  33. }
  34. if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
  35. return nil, 0, err
  36. }
  37. //table.Count(&count)
  38. return doc, int(count), nil
  39. }
  40. func (e *DBColumns) GetList(tx *gorm.DB) ([]DBColumns, error) {
  41. var doc []DBColumns
  42. table := new(gorm.DB)
  43. if e.TableName == "" {
  44. return nil, errors.New("table name cannot be empty!")
  45. }
  46. if config.DatabaseConfig.Driver == "mysql" {
  47. table = tx.Table("information_schema.columns")
  48. table = table.Where("table_schema= ? ", config.GenConfig.DBName)
  49. table = table.Where("TABLE_NAME = ?", e.TableName).Order("ORDINAL_POSITION asc")
  50. } else {
  51. pkg.Assert(true, "目前只支持mysql数据库", 500)
  52. }
  53. if err := table.Find(&doc).Error; err != nil {
  54. return doc, err
  55. }
  56. return doc, nil
  57. }