2020-02-03 05:40:03 +03:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2020-02-22 12:53:57 +03:00
|
|
|
"fmt"
|
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-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{
|
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-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 ""
|
|
|
|
}
|