gorm/dialects/postgres/postgres.go

84 lines
1.6 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-03 05:40:03 +03:00
"github.com/jinzhu/gorm"
"github.com/jinzhu/gorm/callbacks"
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)
db.DB, err = sql.Open("postgres", dialector.DSN)
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{
DB: db,
Dialector: dialector,
}}}
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-03 05:40:03 +03:00
return "?"
}
2020-02-05 06:14:58 +03:00
2020-02-22 12:53:57 +03:00
func (dialector Dialector) QuoteChars() [2]byte {
2020-02-05 06:14:58 +03:00
return [2]byte{'"', '"'} // "name"
}
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 ""
}