gorm/dialects/postgres/postgres.go

99 lines
2.2 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-02-03 05:40:03 +03:00
"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"
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
2020-03-12 08:05:22 +03:00
callbacks.RegisterDefaultCallbacks(db, &callbacks.Config{
WithReturning: true,
})
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-03-09 12:59:54 +03:00
func (dialector Dialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement, v interface{}) {
writer.WriteByte('$')
writer.WriteString(strconv.Itoa(len(stmt.Vars)))
2020-02-03 05:40:03 +03:00
}
2020-02-05 06:14:58 +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-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:
2020-03-12 03:39:42 +03:00
if field.AutoIncrement || field == field.Schema.PrioritizedPrimaryField {
2020-02-22 12:53:57 +03:00
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:
2020-05-31 05:38:01 +03:00
return "timestamptz"
2020-02-22 12:53:57 +03:00
case schema.Bytes:
return "bytea"
}
return ""
}