Add database alias table and fix wrong warning #1947

Merged
lunny merged 3 commits from lunny/add_alias_table into master 2021-07-07 09:09:41 +00:00
6 changed files with 56 additions and 2 deletions

View File

@ -43,6 +43,7 @@ type Dialect interface {
Init(*URI) error
URI() *URI
SQLType(*schemas.Column) string
Alias(string) string // return what a sql type's alias of
FormatBytes(b []byte) string
Version(ctx context.Context, queryer core.Queryer) (*schemas.Version, error)
@ -80,6 +81,11 @@ type Base struct {
quoter schemas.Quoter
}
// Alias returned col itself
func (db *Base) Alias(col string) string {
return col
}
// Quoter returns the current database Quoter
func (db *Base) Quoter() schemas.Quoter {
return db.quoter

View File

@ -190,6 +190,21 @@ func (db *mysql) Init(uri *URI) error {
return db.Base.Init(db, uri)
}
var (
mysqlColAliases = map[string]string{
"numeric": "decimal",
}
)
// Alias returns a alias of column
func (db *mysql) Alias(col string) string {
v, ok := mysqlColAliases[strings.ToLower(col)]
if ok {
return v
}
return col
}
func (db *mysql) Version(ctx context.Context, queryer core.Queryer) (*schemas.Version, error) {
rows, err := queryer.QueryContext(ctx, "SELECT @@VERSION")
if err != nil {

View File

@ -778,12 +778,24 @@ var (
var (
// DefaultPostgresSchema default postgres schema
DefaultPostgresSchema = "public"
postgresColAliases = map[string]string{
"numeric": "decimal",
}
)
type postgres struct {
Base
}
// Alias returns a alias of column
func (db *postgres) Alias(col string) string {
v, ok := postgresColAliases[strings.ToLower(col)]
if ok {
return v
}
return col
}
func (db *postgres) Init(uri *URI) error {
db.quoter = postgresQuoter
return db.Base.Init(db, uri)

View File

@ -286,6 +286,19 @@ func TestSyncTable3(t *testing.T) {
}
}
func TestSyncTable4(t *testing.T) {
type SyncTable6 struct {
Id int64
Qty float64 `xorm:"numeric(36,2)"`
}
assert.NoError(t, PrepareEngine())
assert.NoError(t, testEngine.Sync2(new(SyncTable6)))
assert.NoError(t, testEngine.Sync2(new(SyncTable6)))
}
func TestIsTableExist(t *testing.T) {
assert.NoError(t, PrepareEngine())

View File

@ -365,3 +365,9 @@ func SQLType2Type(st SQLType) reflect.Type {
return reflect.TypeOf("")
}
}
// SQLTypeName returns sql type name
func SQLTypeName(tp string) string {
fields := strings.Split(tp, "(")
return fields[0]
}

View File

@ -336,8 +336,10 @@ func (session *Session) Sync2(beans ...interface{}) error {
}
} else {
if !(strings.HasPrefix(curType, expectedType) && curType[len(expectedType)] == '(') {
engine.logger.Warnf("Table %s column %s db type is %s, struct type is %s",
tbNameWithSchema, col.Name, curType, expectedType)
if !strings.EqualFold(schemas.SQLTypeName(curType), engine.dialect.Alias(schemas.SQLTypeName(expectedType))) {
engine.logger.Warnf("Table %s column %s db type is %s, struct type is %s",
tbNameWithSchema, col.Name, curType, expectedType)
}
}
}
} else if expectedType == schemas.Varchar {