gorm/dialects/mssql/mssql.go

76 lines
1.5 KiB
Go
Raw Normal View History

2020-02-22 12:53:57 +03:00
package mssql
import (
"database/sql"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/callbacks"
"github.com/jinzhu/gorm/migrator"
"github.com/jinzhu/gorm/schema"
)
type Dialector struct {
DSN string
}
func Open(dsn string) gorm.Dialector {
return &Dialector{DSN: dsn}
}
func (dialector Dialector) Initialize(db *gorm.DB) (err error) {
// register callbacks
callbacks.RegisterDefaultCallbacks(db)
db.DB, err = sql.Open("sqlserver", dialector.DSN)
return
}
func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator {
return Migrator{migrator.Migrator{Config: migrator.Config{DB: db}}}
}
func (dialector Dialector) BindVar(stmt *gorm.Statement, v interface{}) string {
return "?"
}
func (dialector Dialector) QuoteChars() [2]byte {
return [2]byte{'[', ']'} // `name`
}
func (dialector Dialector) DataTypeOf(field *schema.Field) string {
switch field.DataType {
case schema.Bool:
return "bit"
case schema.Int, schema.Uint:
var sqlType string
switch {
case field.Size < 16:
sqlType = "smallint"
case field.Size < 31:
sqlType = "int"
default:
sqlType = "bigint"
}
if field.AutoIncrement {
return sqlType + " IDENTITY(1,1)"
}
return sqlType
case schema.Float:
return "decimal"
case schema.String:
if field.Size > 0 && field.Size <= 4000 {
return fmt.Sprintf("nvarchar(%d)", field.Size)
}
return "ntext"
case schema.Time:
return "datetimeoffset"
case schema.Bytes:
return "binary"
}
return ""
}