gorm/dialects/mssql/mssql.go

96 lines
2.1 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-02-22 12:53:57 +03:00
_ "github.com/denisenkom/go-mssqldb"
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/callbacks"
2020-03-09 12:07:00 +03:00
"github.com/jinzhu/gorm/clause"
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
}
2020-03-09 12:59:54 +03:00
func (dialector Dialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement, v interface{}) {
writer.WriteString("@p")
writer.WriteString(strconv.Itoa(len(stmt.Vars)))
2020-02-22 12:53:57 +03:00
}
2020-03-09 12:07:00 +03:00
func (dialector Dialector) QuoteTo(writer clause.Writer, str string) {
writer.WriteByte('"')
writer.WriteString(str)
writer.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"
}
2020-03-12 03:39:42 +03:00
if field.AutoIncrement || field == field.Schema.PrioritizedPrimaryField {
2020-02-22 12:53:57 +03:00
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 ""
}