Skip to content

Commit

Permalink
Merge pull request #3 from go-gorm/feat_tableType
Browse files Browse the repository at this point in the history
feat: support TableType
  • Loading branch information
qqxhb authored Sep 3, 2023
2 parents 9f1bd83 + 64007b2 commit 1161f43
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
18 changes: 18 additions & 0 deletions migrator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package rawsql

import (
"database/sql"
"strings"

"gorm.io/gorm"
Expand All @@ -12,6 +13,23 @@ type Migrator struct {
Dialector
}

func (m Migrator) TableType(value interface{}) (tableType gorm.TableType, err error) {
err = m.RunWithValue(value, func(stmt *gorm.Statement) error {
var (
schema, tableName = m.CurrentSchema(stmt, stmt.Table)
)
table, ok := m.tables[tableName]
if ok && table != nil {
tableType = &migrator.TableType{
SchemaValue: schema,
NameValue: tableName,
CommentValue: sql.NullString{String: table.Comment, Valid: true},
}
}
return nil
})
return tableType, err
}
func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) {
columnTypes := make([]gorm.ColumnType, 0)
err := m.RunWithValue(value, func(stmt *gorm.Statement) error {
Expand Down
7 changes: 5 additions & 2 deletions table.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"reflect"
"strconv"
"strings"
"time"

"github.com/pingcap/tidb/parser"
Expand All @@ -20,6 +21,7 @@ type Table struct {
ColumnTypes []gorm.ColumnType
Indexes []gorm.Index
Name string
Comment string
}

type Parser interface {
Expand Down Expand Up @@ -59,6 +61,7 @@ func (d *defaultParser) ParseSQL(sql string) error {

d.tables[tableName] = &Table{
Name: tableName,
Comment: create.Table.TableInfo.Comment,
ColumnTypes: d.getColumnTypes(create),
Indexes: d.getIndexes(create),
}
Expand Down Expand Up @@ -177,9 +180,9 @@ func (*defaultParser) getColumnType(col *ast.ColumnDef) gorm.ColumnType {
NameValue: sql.NullString{Valid: true, String: col.Name.OrigColName()},
DataTypeValue: sql.NullString{
Valid: true,
String: types.TypeToStr(col.Tp.GetType(), col.Tp.GetCharset()),
String: strings.ToLower(types.TypeToStr(col.Tp.GetType(), col.Tp.GetCharset())),
},
ColumnTypeValue: sql.NullString{Valid: true, String: col.Tp.String()},
ColumnTypeValue: sql.NullString{Valid: true, String: strings.ToLower(col.Tp.String())},
PrimaryKeyValue: sql.NullBool{
Bool: mysql.HasPriKeyFlag(col.Tp.GetFlag()),
Valid: mysql.HasPriKeyFlag(col.Tp.GetFlag()),
Expand Down

0 comments on commit 1161f43

Please sign in to comment.