gorm/dialects/mssql/mssql.go

95 lines
2.0 KiB
Go
Raw Normal View History

2020-02-22 12:53:57 +03:00
package mssql
import (
"database/sql"
"fmt"
2020-02-23 07:39:26 +03:00
"regexp"
2020-02-22 20:02:07 +03:00
"strconv"
2020-03-08 18:30:16 +03:00
"strings"
2020-02-22 12:53:57 +03:00
_ "github.com/denisenkom/go-mssqldb"
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/callbacks"
2020-02-23 07:39:26 +03:00
"github.com/jinzhu/gorm/logger"
2020-02-22 12:53:57 +03:00
"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)
2020-03-09 08:10:48 +03:00
db.ConnPool, err = sql.Open("sqlserver", dialector.DSN)
2020-02-22 12:53:57 +03:00
return
}
func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator {
2020-02-22 14:41:01 +03:00
return Migrator{migrator.Migrator{Config: migrator.Config{
2020-02-22 20:02:07 +03:00
DB: db,
Dialector: dialector,
CreateIndexAfterCreateTable: true,
2020-02-22 14:41:01 +03:00
}}}
2020-02-22 12:53:57 +03:00
}
func (dialector Dialector) BindVar(stmt *gorm.Statement, v interface{}) string {
2020-02-22 20:02:07 +03:00
return "@p" + strconv.Itoa(len(stmt.Vars))
2020-02-22 12:53:57 +03:00
}
2020-03-08 18:30:16 +03:00
func (dialector Dialector) QuoteTo(builder *strings.Builder, str string) {
builder.WriteByte('"')
builder.WriteString(str)
builder.WriteByte('"')
2020-02-22 12:53:57 +03:00
}
2020-02-23 07:39:26 +03:00
var numericPlaceholder = regexp.MustCompile("@p(\\d+)")
func (dialector Dialector) Explain(sql string, vars ...interface{}) string {
return logger.ExplainSQL(sql, numericPlaceholder, `'`, vars...)
}
2020-02-22 12:53:57 +03:00
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:
2020-02-22 20:02:07 +03:00
size := field.Size
2020-02-23 03:29:59 +03:00
if field.PrimaryKey && size == 0 {
2020-02-22 20:02:07 +03:00
size = 256
}
if size > 0 && size <= 4000 {
return fmt.Sprintf("nvarchar(%d)", size)
2020-02-22 12:53:57 +03:00
}
return "ntext"
case schema.Time:
return "datetimeoffset"
case schema.Bytes:
return "binary"
}
return ""
}