gorm/dialects/postgres/postgres.go

96 lines
2.0 KiB
Go
Raw Normal View History

2020-02-03 05:40:03 +03:00
package postgres
import (
"database/sql"
2020-02-22 12:53:57 +03:00
"fmt"
2020-02-23 07:39:26 +03:00
"regexp"
2020-02-22 19:40:06 +03:00
"strconv"
2020-03-08 18:30:16 +03:00
"strings"
2020-02-03 05:40:03 +03:00
"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"
2020-02-03 05:40:03 +03:00
_ "github.com/lib/pq"
)
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("postgres", dialector.DSN)
2020-02-03 05:40:03 +03:00
return
}
2020-02-22 12:53:57 +03:00
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 19:40:06 +03:00
DB: db,
Dialector: dialector,
CreateIndexAfterCreateTable: true,
2020-02-22 14:41:01 +03:00
}}}
2020-02-03 05:40:03 +03:00
}
2020-02-22 12:53:57 +03:00
func (dialector Dialector) BindVar(stmt *gorm.Statement, v interface{}) string {
2020-02-22 19:40:06 +03:00
return "$" + strconv.Itoa(len(stmt.Vars))
2020-02-03 05:40:03 +03:00
}
2020-02-05 06:14:58 +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-05 06:14:58 +03:00
}
2020-02-22 12:53:57 +03:00
2020-02-23 07:39:26 +03:00
var numericPlaceholder = regexp.MustCompile("\\$(\\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 "boolean"
case schema.Int, schema.Uint:
if field.AutoIncrement {
switch {
case field.Size < 16:
return "smallserial"
case field.Size < 31:
return "serial"
default:
return "bigserial"
}
} else {
switch {
case field.Size < 16:
return "smallint"
case field.Size < 31:
return "integer"
default:
return "bigint"
}
}
case schema.Float:
return "decimal"
case schema.String:
if field.Size > 0 {
return fmt.Sprintf("varchar(%d)", field.Size)
}
return "text"
case schema.Time:
return "timestamp with time zone"
case schema.Bytes:
return "bytea"
}
return ""
}